Analysis of Kotlin coroutine
Article directory
-
- What is a coroutine
- Use of a coroutine
-
- Create & start a coroutine
- Coroutine scheduling
- Advantages of coroutines
What is a coroutine
Coroutine is a concurrency design pattern that can be used to simplify code that executes asynchronously. The coroutine does not abandon the thread mechanism to stand on its own, because in essence, the coroutine is also implemented through the thread pool when executing asynchronous tasks, but the coroutine can switch freely between threads. Compared with the callback, the coroutine is simpler.
Use of coroutines
Coroutines are most commonly used in concurrent scenarios, and the total execution time of using coroutines in a single thread will not be less than without coroutines.
Create & start coroutine
Function suspend and resume
Coroutines add two operations to conventional functions, which can handle time-consuming tasks more gracefully. In addition to invoke (or call) and return of regular functions, coroutines add suspend and resume:
- suspend: Suspend the execution of the current coroutine and save all local variables.
- resume: Used for the suspended coroutine to resume execution from the suspension.
kotlThe suspension and recovery of the in coroutine is essentially the suspension and recovery of the function. How does kotlin do it
Two ways to start a coroutine:
- launch: You can start a new coroutine, and will not return the result to the caller
- async: You can start a new coroutine, and allow the use of await to suspend the function to return the result
Among them, the launch function is not a top-level function and cannot be used directly. You can create a coroutine in the following three ways:
-
runBlocking: runBlocking is a top-level function that can directly create coroutines. Not suitable for development, because it is thread-blocked, it can be used for unit testing
-
GlobalScope: GlobalScope singleton objects open coroutines, life The cycle is consistent with Application and cannot be canceled, and it is also not recommended in Android.
-
CoroutineScope: Create a CoroutineScope object through CoroutineContext by yourself, which requires a parameter of type CoroutineContext. This method is recommended for creating coroutines in Android .
Coroutine scheduling
Kotlin provides three schedulers, which can be used to specify which thread the coroutine will execute in. In Kotlin, all coroutines must be executed in the scheduler: if the coroutine needs to be executed in a non-main thread, then the coroutine needs to be specified on the Default or IO scheduler; if the coroutine needs to be executed in the main thread, then Execute the coroutine on the Main scheduler. Here are the specific instructions:
- Dispatchers.Main – Use this dispatcher to run coroutines on the Android main thread.This scheduler should only be used to interact with the interface and perform quick work. Examples include calling suspend functions, running Android UI framework operations, and updating LiveData objects.
- Dispatchers.IO – This dispatcher is optimized for performing disk or network I/O outside of the main thread. Examples include using Room components, reading data from or writing data to files, and running any network operations.
- Dispatchers.Default – This dispatcher is optimized for performing CPU-intensive work outside of the main thread. Examples of use cases include sorting lists and parsing JSON.
Advantages of coroutines
Imagine a scenario where the UI update needs to wait for multiple network requests to be executed in parallel. If the callback method is used, it may be troublesome and awkward. If multiple network requests use serial requests, it will take a relatively long time. Compared with parallelism, it will be greatly increased; and if coroutines are used, multiple parallel requests can be written in a serial manner, and the execution results can be combined.
- Safer code: Kotlin provides many language features to avoid the most common exceptions such as null pointers in Java
- The syntax is concise and expressive: Compared with Java, kotlin Do more with less code.
- Interoperable: seamlessly interoperable with the Java language. That is, you can call Java code in kotlin code, and you can also call kotlin code in Java code. The kotlin code is essentially compiled by the kotlin compiler to generate a bytecode that the VM can recognize.
- Structured concurrency: Use a seemingly blocking style of writing to implement asynchronous functions. Compared with the callback method, it greatly simplifies the management of background tasks, such as the management of network requests, database access and other tasks.