Hi, new student. I am glad that you are finally pursuing this question. Maybe you are feeling confused and different people have different understandings of coroutines. Some people say it is a thread framework, while others say it is lighter than threads.
Believe me, any explanation may have changed by the time it comes out of the second person’s mouth. And the website is the most necessary gateway to any technology. So please open Kotlin Chinese. Many people say that the tutorials on Kotlin’s website are not very detailed. Back to business:
What is a coroutine?
- Asynchronous programming
- experience
- Language level
- concept
Notice the key points above and some practical uses, it’s not hard to understand
Kotlin coroutines is based on the Kotlin grammar which extends an asynchronous programming framework, it does not bring much performance experience, it can realize, you use a thread pool also can be implemented, but for using Angle, coroutines efforts to forge a “synchronous and asynchronous programming ideas, as developers, we can more lazy, Switching threads withContext, coroutines bring development comfort, but that comfort is based on Kotlin’s syntax and nothing else. So what I want you to do when you look at coroutines is to try to understand them from a linguistic point of view.
So, what is a coroutine?
The coroutine is an asynchronous framework based on Kotlin syntax that allows developers to write asynchronous code in a synchronous manner without having to worry about redundant operations. It’s that simple
How do coroutines work?
Start a coroutine
suspend fun main(a) {
GlobalScope.launch {
println("Start -${System.currentTimeMillis()}---${Thread.currentThread().name}")
delay(100)
println("Hang ms - 100${System.currentTimeMillis()}---${Thread.currentThread().name}")
}
delay(1000)}Copy the code
Start --1579085375166-- DefaultDispatcher-worker-1 Suspend 100ms--1579085375275-- DefaultDispatcher-worker-1Copy the code
Concurrent use of
fun main(a) {
runBlocking(Dispatchers.IO) {
println("Start -${System.currentTimeMillis()}")
val as1 = async {
delay(100)
println(1 - "concurrent${System.currentTimeMillis()}---${Thread.currentThread().name}")
"1"
}
val as2 = async {
delay(100)
println(2 - "concurrency${System.currentTimeMillis()}---${Thread.currentThread().name}")
"2"
}
println("as1=${as1.await()},as2=${as2.await()}")}}Copy the code
Start -1579085205199concurrent1--1579085205313---DefaultDispatcher-worker-3concurrent2--1579085205313---DefaultDispatcher-worker-2
as1=1,as2=2
Copy the code
Looking at the results of the demo above, is it comfortable? It looks like the synchronous mode is working asynchronously inside. So what do I mean by suspend in the above comment?
What is suspension?
Looking at the print log above, it is not hard to see that when the delay function is called, the thread does not stop, but rather that our coroutine block is suspended, waiting to resume. Our coroutine block cannot continue execution until the previous suspension function completes. Here’s a picture to illustrate:
So the so-called hang is actually a process at the code level that allows us to write asynchronous code in synchronous form.
Non-blocking program?
As we can see, when we directly launch a coroutine globalScope. launch, the default thread is running, so the coroutine is called a non-blocking implementation.
The suspend keyword role
Take a look at the picture below
When we use a suspend function we call it a suspend function. What does the suspend function do? Why is the suspend flag for test black?
Keep looking at the screenshots
Why y can suspend functions only be used in suspend functions?
Let’s move on: Look at Java bytecode
What is this Continuation? Literally, it means continuation. So what are we to make of that?
In general, continuations stand for “the concept of remaining computation,” the code to be executed next. The official explanation is called hanging point
Let’s say I have a piece of code:
println("123".length)
Copy the code
The first one is “123”. Length, and the second one is “123”. Length, and the second one is “123”. At this point we proceed to execute our print statement.
Switch to our suspend function, which represents the action of a flag. A function decorated with suspend is called a suspend function. When the compiler encounters this flag, it knows that it is a potentially time-consuming operation.
Why should suspended functions only be used in suspended functions?
The compiler can’t tell if a function argument has a Continuation, so it raises an error.
Why is the suspend flag for test black?
The compiler knows that test is a suspend function, but there is no suspend function inside test.
So this function doesn’t work at all?
It does limit this function to suspending only function calls.
Use in Android
Countdown function
class Main3Activity : AppCompatActivity() {
private val mainScope = CoroutineScope(Dispatchers.Default)
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main3)
progressBar.max = 100
mainScope.launch {
(1.100.).forEach {
delay(100)
withContext(Dispatchers.Main) {
progressBar.secondaryProgress = it
}
}
}
}
onDestory(){
// Remember to close}}Copy the code
Use in conjunction with the ViewModel
class MainViewModel : ViewModel() {
fun test(a) {
viewModelScope.launch {
}
}
}
Copy the code
When the ViewModel cancels, the coroutine closes automatically
Use with Lifecycle
Import the following dependencies
Implementation "androidx lifecycle: lifecycle - runtime - KTX: 2.2.0 - rc03"Copy the code
So the countdown code is changed to the following:
class Main3Activity : AppCompatActivity() {... lifecycleScope.launch { ... }}}Copy the code
Similarly, the coroutine will automatically close when the Fragment or Activity is closed.
Lifecycle lifecycleScope will be implemented in the same way as viewModelScope:
In this article, we do not pursue too much from the source code, what is the coroutine, try to start from the syntax, the user’s point of view, with everyone to understand the coroutine from the side, I hope everyone can have their own understanding.
If you want to dig deeper, the following blogs are recommended:
Beenyhuo