preface

I believe many people in Android use coroutines to handle various asynchronous scenarios. Even Flow can play like a duck to water. This article will teach you how to convert other code into suspend functions to make your coroutine more comfortable to use.

Another thing we should know is that a coroutine is essentially a threading tool.

suspendCoroutine & suspendCancellableCoroutine

When we start a coroutine, if we come across code written by somebody else or code in some SDK. It provides the result in the form of Callback. The code might look like this:

Obviously, you still use callback hell. Extremely ugly code. And you can’t reuse it.

SuspendCoroutine can help you solve this problem by converting an asynchronous or callback code to a suspended function.

SuspendCoroutine suspends the current coroutine until the internal block returns a correct or incorrect message using cot.resume() or cot.resumeWithexception ().

The suspended coroutine will continue.

So suspendCoroutine is important to get your entire coroutine code out of callback hell.

SuspendCancellableCoroutine just as its name implies, is a more than suspendCoroutine cancel callback. This means that when the coroutine cancels, it gives you an opportunity to cancel the operation. For example:

async

We often use async for concurrency in coroutines, as in the following scenario. Asynchronously get two user information. And then do the rest after you get it

In this small example, we get two user information concurrently and concatenate the names of the two users. The core is:

Async returns a Deferred object. We can then suspend the coroutine by calling the deferred.await () method. A must for home travel.

Reactive

Coroutines officially provide transformations to common reactive flows.

The link is: github.com/Kotlin/kotl…

For example, RxJava transformation is provided. Use the related method beginning with await

conclusion

In this article, I’ve introduced a few common ways to make your coroutine code execute sequentially.

Read all read, pay attention to my public number