Who has not read the documentation - I strongly recommend to read.
What does the Jetbrains write:
Coroutines simplify asynchronous programming, leaving all the complications inside libraries. The program logic can be expressed sequentially in coroutines, and the core library will implement it asynchronously for us. The library can wrap the relevant parts of the user code in callbacks subscribing to the relevant events, and dispatch execution to different threads (or even to different machines!). The code at the same time will remain as simple as if it was executed strictly consistently.
In simple terms, this is a library for synchronous \ asynchronous code execution.
What for?
Because RxJava is no longer in fashion (joke).
Firstly, I wanted to try something new, and secondly, I came across an article - comparing the speed of work of corutin and other methods.
Example
For example, you need to perform an operation in the background.
First, let's add a dependency on corutin to our build.gradle:
Where in context - we specify the thread pool we need - in simple cases it is IO, Main and Default
IO - for simple operations with the API, database operations, shared preferencies, and so on. Main - UI thread from where we can access the view Default - for heavy operations with high CPU load (More in this article )
In principle, this is all, we get the result of the sum of squares from 1 to 1000 and at the same time do not block the main thread which means - no ANR
However, if our korutin is fulfilled for 20 seconds and during this time we made 2 turns of the device, then we will have 3 simultaneously executed blocks. Oops.
And if we passed a link to the activity to the block, there is a leak and the lack of the ability in old blocks to perform operations with view. Double oops.
Thus, we were able to stop the execution of our code in the stream, for example, when turning the screen.
CoroutineScope made it possible to combine the scope of all nested coruntines and, when calling job.cancel (), stop their execution
If you plan to reuse the scope after stopping the execution, you need to use job.cancelChildren () instead of job.cancel (), thanks Neikist for commenting
At the same time, we still have the ability to manage flows:
fundoWork() {
var result =1.0
var result2 =1.0
viewModelScope.launch {
withContext(IO) {
for (i in1..1000) {
result += i * i
}
}
withContext(Default) {
for (i in1..1000) {
result2 += i * i
}
}
}
Log.d("coroutines example", "running result = $result, result 2 = $result2")