Kotlin Coroutines the right way in Android

前端 未结 9 1114
醉酒成梦
醉酒成梦 2020-12-02 06:51

I\'m trying to update a list inside the adapter using async, I can see there is too much boilerplate.

Is it the right way to use Kotlin Coroutines?

can this

9条回答
  •  醉酒成梦
    2020-12-02 07:18

    Here's the right way to use Kotlin Coroutines. Coroutine scope simply suspends the current coroutine until all child coroutines have finished their execution. This example explicitly shows us how child coroutine works within parent coroutine.

    An example with explanations:

    fun main() = blockingMethod {                    // coroutine scope         
    
        launch { 
            delay(2000L)                             // suspends the current coroutine for 2 seconds
            println("Tasks from some blockingMethod")
        }
    
        coroutineScope {                             // creates a new coroutine scope 
    
            launch {
                delay(3000L)                         // suspends this coroutine for 3 seconds
                println("Task from nested launch")
            }
    
            delay(1000L)
            println("Task from coroutine scope")     // this line will be printed before nested launch
        } 
    
        println("Coroutine scope is over")           // but this line isn't printed until nested launch completes
    }
    

    Hope this helps.

提交回复
热议问题