Kotlin: Coroutines scope vs Coroutine context

前端 未结 3 1946
梦谈多话
梦谈多话 2020-12-29 04:32

Can anyone explain the difference between them? I think scope provides a reference(e.g. Job) to cancel them and context provides a reference to underlying thread. Is that so

3条回答
  •  伪装坚强ぢ
    2020-12-29 04:46

    CoroutineScope has-a CoroutineContext.

    For example if you have:

    runBlocking { // defines coroutineScope
    
        launch(Dispatchers.Default) { //inherits coroutineScope but changes context
    
        }
    }
    

    runBlocking defines a CoroutineScope (learn about it here) which launch inherits. The context is being overridden by explicitly specifying a dispatcher here. If you look at the definition of launch, you can see that it takes an optional CoroutineContext:

    public fun CoroutineScope.launch(
        context: CoroutineContext = EmptyCoroutineContext,
        ...
    )
    

    Another part of the context would be the coroutine's name:

    launch(CoroutineName("launchMe") + Dispatchers.Default) {
        println("")
    }
    

提交回复
热议问题