From beginning to end, there are two words: simple.
First, the introduction of coprogramming libraries in Android projects
Quite simply, in Kotlin’s Android project, add two dependency libraries and you can enjoy coroutines.
Commit: github.com/vectorzeng/…
implementation 'org. Jetbrains. Kotlinx: kotlinx coroutines -- core: 1.3.3'
implementation 'org. Jetbrains. Kotlinx: kotlinx coroutines - android: 1.3.3'
Copy the code
The two lib source repositories are:
-
Github.com/Kotlin/kotl…
-
Github.com/Kotlin/kotl…
Switch threads through coroutines
Coroutine makes thread switching even simpler.
The following code: github.com/vectorzeng/…
override fun onCreate(savedInstanceState: Bundle?). {
// Context switch to IO main thread
GlobalScope.launch(Dispatchers.IO) {
Log.i(TG, "Dispatchers.IO isMainThread ${isMain()}")/ / output is false
// Switch the context to the main thread
GlobalScope.launch(Dispatchers.Main){
Log.i(TG, "Dispatchers.Main isMainThread ${isMain()}")/ / output true}}}Copy the code
Log output result:
Simple?
Compared to Java handler, Thread, rxJava, is not simple let a person feel that he is a bit beautiful ~
MMM, it smells good
Key words: Android; kotlin ; coroutines ; hello coroutines ; coroutine switch to thread ; coroutine to main thread ; coroutine switch io thread ; Introduction to Kotlin coroutines; Android thread switch; Kotlin coroutine thread switching;