Initial understanding of kotlin coroutine

kotlin coroutine understanding

Initial cognition

  1. Kotlin coroutine is a thread library; alternatives are: AsyncTask, Handler+thread pool, RxJava
  2. The advantages of kotlin coroutine compared with other programs:
  • Lightweight: The smallest unit of other multi-task asynchronous solutions is a thread, and the coroutine is on top of the thread, which can share threads, maximize reuse, and consume a small amount of resources to create a large number of coroutines
  • Easy for management and control: support coroutine cancellation and structural concurrency, unified scope management

Why use coroutines in kotlin

  1. Let’s take a look at the asynchronous task of loading a list data from the network without coroutines
 private fun loadData1() {
        loadListData1 {
            runOnUiThread {
                show.text = it.toString();
            }
        }
    }
    private fun loadListData1(callback: (dataList: List) -> Unit) {
        Thread {
            Thread.sleep(2000)//simulation network time-consuming
            callback.invoke(mutableListOf().apply {
                add("item1")
                add("item2")
                add("item3")
            })
        }.start()
    }

You can see that the main business logic code has two layers of nesting (using java will have more nesting), a single simple business request is not obvious, if the business is complex, the callback hell is obvious, and it is not easy to maintain
2. Use kotlin coroutine to achieve

 var mainScope = MainScope();
    private fun loadData2() {
        mainScope. launch {
            val loadListData = loadListData2()
            show.text = loadListData.toString();
        }

    }
    private suspend fun loadListData2(): List = withContext(Dispatchers.IO) {
        Thread.sleep(2000)//simulation network time-consuming
        mutableListOf().apply {
            add("item1")
            add("item2")
            add("item3")
        }
    }

You can see the code implemented using kotlin coroutines. The main business logic code is very clear, which is equivalent to synchronous code for writing a single task

What is in the coroutine in kotlin

Class in kotlin coroutine

Class/Interface Function
CoroutineScope It is the scope of the coroutine, which is used to control the life cycle of the coroutine
CombinedContext Provides the information needed for the coroutine to start and run
Dispatchers Specify the thread that the coroutine runs (IO, Default, Main, Unconfined)
CoroutineStart specifies the start mode of the coroutine. It is an enumeration value. The default is to start immediately. It can also be changed to delayed start by specifying CoroutineStart.LAZY. The delayed start requires you to actively call the returned Job object. The coroutine will start after the start method

How to use coroutines in Android

By customizing CoroutineScope, you can enable or control the life cycle of coroutines at a certain level of the application. For example, Android provides CoroutineScope in the life cycle of ViewModel and Lifecycle classes, which are ViewModelScope and LifecycleScope.

Demystifying CoroutineContext in Kotlin Coroutine

Leave a Reply

Your email address will not be published. Required fields are marked *