Coroutines: a practical vocabulary

栏目: IT技术 · 发布时间: 4年前

内容简介:Coroutines is a powerful feature that makes running async work easy in Kotlin.It's quite easy to get started with coroutines and running work in the non-main thread by copying-pasting code from the web (and most of the time it's fine).If you already did th

Coroutines is a powerful feature that makes running async work easy in Kotlin.

It's quite easy to get started with coroutines and running work in the non-main thread by copying-pasting code from the web (and most of the time it's fine).

If you already did that but you would like to understand the bare basics about those context, scope and other objects you are using  you are reading the right blog post :)

Coroutine Context

A coroutine executes always in a Context . The context is a group of other objects, most notably the Job and Dispatcher which are explained below.

Job

Represents a background job. It's cancellable, and you can arrange jobs in parent-child hierarchies.

When you launch a coroutine within a coroutine, it inherits the Coroutine Context. The Job of the new coroutine becomes child of the parent's coroutine Job. Therefore, when the parent coroutine is canceled, all its children are recursively canceled too.

launch {
    // This coroutine has a Context that contains a Job (a.k.a parent Job).
    [...]
    
    launch {
        // This coroutine's Job, is a child of parent Job
        [...]
    }
}
Launching a child coroutine

Dispatcher

Determines which thread(s) the coroutine uses for the execution.

When launching a child coroutine (as seen above), you can override the Dispatcher by passing it to the launch() method.

launch {
    // This coroutine has a Context that contains a Job and a Dispatcher.
    [...]
    
    launch(Dispatchers.IO) {
        // In this child coroutine the Dispatcher has been overriden.
        [...]
    }
}
Launching a child coroutine and overriding the Dispatcher

To change Dispatcher within the same coroutine, use withContext() (the context  inside the withContext block is the existing context plus the provided) .

launch {
    withContext(Dispatchers.IO) {
        // This is the same coroutine, with the Dispatcher overriden.
    	[...]
    }
}
Switching Dispatcher without launching a coroutine

Coroutine scope

Essentially a class that contains a Coroutine context . It exists to manage the lifecycle of coroutines (without manipulating contexts and jobs manually).

But why have another class if it just contains the context? tl;dr: Because they serve a different purpose ( longer explanation ).

Most of the time, the scope is attached to objects that we want to stop all coroutines they launched when they stop to exist (e.g. Activities, ViewModels, etc).

All the coroutine builders methods you've seen (e.g. launch , async ) are extension methods of Coroutine context .

To use a scope:

  • Create it (and manage it) manually:
class Activity {
    private val mainScope = MainScope()
    
    fun destroy() {
        mainScope.cancel()
    }
    
    fun doSomething() {
        mainScope.launch {
            [...]
        }
    }
 }
  • Use delegation:
class Activity : CoroutineScope by CoroutineScope(Dispatchers.Default) {
    
    fun doSomething() {
        // Note that the scope is implied here
        launch {
            [...]
        }
    }
}
  • Use provided scope:
class MyViewModel : ViewModel() {

    fun doSomething() {
        // Android Jetpack ViewModel, provide a scope attached to VM lifecycle
        viewModelScope.launch {
            [...]
        }
    }
}

Hopefully, these coroutine related concepts are a bit more clear now!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

人人都在晒,凭什么你出彩

人人都在晒,凭什么你出彩

【美】奥斯丁•克莱恩 / 张舜芬、徐立妍 / 北京联合出版公司 / 2015-4 / 38.00

1. 《纽约时报》、亚马逊畅销书排名第1位、好评如潮的创意营销书。《出版人周刊》称其在社交网络时代“在安全范围内提供了实用的自我营销策略”。 2. TED演讲者创意分享:晒对了,全世界都为你点赞:别人在朋友圈、微博晒自拍、晒孩子、晒吃喝,你来晒创意、晒灵感、晒工作、晒收获,发出自己的声音,找到伙伴,机会也会主动找上门! 3. 10堂创意课+手绘涂鸦,所有人都能轻松读完、迅速学会的创意小......一起来看看 《人人都在晒,凭什么你出彩》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

随机密码生成器
随机密码生成器

多种字符组合密码