Why coroutines

The most difficult part of Kotlin is the coroutine, and it’s the one I spend the most time on (1-2 months before and after), going through official documents and other people’s articles countless times. I’m not sure I can say this clearly, but I do have a few ideas about the basic application & coroutine design concepts and some of the principles.

What is a coroutine

  1. Coroutines iskotlinProvides us with the thread switching framework, which andAsyncTaskRxJavaDo the same thing.
  2. Coroutines do not improve efficiency, only code readability.
  3. Coroutines are not threads; they are only responsible for switching threads.

Android thread switching history

Before we talk about what works, let’s talk about the history of Android thread switching.

Before explaining a reminder of a practical use case, you can think about how you would implement this thread switching technique. 1: an interface needs two interfaces to successfully request at the same time. When both interfaces successfully request, render the interface (note: two interfaces need to request in two threads). 2:1 An interface requires sequential requests from two interfaces. The second interface relies on the data returned by the first interface as a parameter.

  1. Handler switch someone would say: useHandlerYou had fun switching, didn’t you? I useHandlerSwitching threads is awesome. I don’t evenHandlerThe principle is clear as day. The fatal drawback of switching threads in this way isThe callback hell.

  1. AsyncTask encapsulates realityAsyncTaskIt encapsulates asynchronous tasks (as if all frameworks are encapsulates). However, the problem of hell callback cannot be avoided by treating the symptoms rather than the root cause, and many scenarios cannot be used.

  1. All the way to theRxJavaThe emergence ofAndroidThe problem has been alleviated. When I first used itRxJavaI found it really useful, but I found it very expensive to learn. The complexity of the operators, and how they work, is very difficult to understand. Let meRxJavaFrom getting started to giving up.

At this point, you should find that each of the above three solutions has some disadvantages, and the best solution is that RxJava’s drain line thread is more intelligent, and exceptions can be managed uniformly.

  1. KotlinWith the introduction of the new thread cutting scheme, asynchronous functionality can be written in synchronous code.

Coroutines

From the above, we know that all thread frameworks want to solve one problem: the hell-callback problem. So what would our ideal thread switch look like? Take a look at the pseudocode:

void initView(a) {
    // Main thread shows loading DialogShow loading Dialog()// Asynchronous network requests wait for data to returnVal data = Request network data asynchronously ()// dismissDialog();Disappear Dialog ()// Main thread renders the ViewModify View state (data)}Copy the code

Look at the pseudo code above, you think about Java can achieve this function? If you think about it, it’s impossible to implement such code in Java. The syntax doesn’t support it. There’s no way asynchronous methods can return data in Java. Finally, coroutines were created to solve this problem. Who says Java doesn’t support it, and how can Kotlin’s son support it? Koltin can actually implement this code because Kotlin’s compiler plays tricks on your eyes.

fun initView(a) Start a coroutine {// 1: main thread shows loading DialogShow loading Dialog()// 2: asynchronous network request, execute a suspend functionVal data = Request network data asynchronously ()// 1: dismissDialog();Dialog()}}Copy the code

Looking at the pseudocode at the top, we started a coroutine first, and the rest is basically three lines of code, the first line of code is not much to say.

The point is that the second line of code coroutines have this concept of a hang, which means I’m going to execute a hang function, call my main thread and you can go do something else, and when I’m done I’ll call you, execute my third line of code.

Does the second explanation of the code look like a callback? Isn’t the function of the callback we always write to tell us when we’re done?

In fact, Kotlin’s coroutine suspend function implementation principle is through callback to achieve. Kotlin’s compiler is playing tricks on your eyes because it looks like 1, 2, 3 lines of code are written together, but the compiled Class bytecode is not.

conclusion

So with that explanation, let’s finally summarize Kotlin’s coroutine, okay?

  • The purpose of coroutines is to allow us to write asynchronous functionality in synchronous code
  • The coroutine is responsible for helping us switch threads after executing the suspend function
  • Suspension functions are also ultimately implemented through callback functions
  • The synchronous code written by coroutines appears to be written together, but is actually separated from the suspended function after the final compilation.

Finally, don’t look at Kotlin’s coroutines in the same way you look at Java code, or you’ll end up in a closed loop. Because sometimes what your eyes see is not the same as the resulting Java code, Kotlin’s compiler can trick your eyes.