0%

Kotlin协程

配置(Android)

1
2
// kotlin coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.5'

示例:加载网络图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val coroutineScope = CoroutineScope(Dispatchers.Main)
coroutineScope.launch(Dispatchers.Main) {
val url = getImageUrl()
Glide.with(this@MainActivity).load(url).into(iv)
}

}

private suspend fun getImageUrl() = withContext(Dispatchers.IO) {
val client = OkHttpClient()
val request = Request.Builder()
.url("http://guolin.tech/api/bing_pic")
.build()
return@withContext client.newCall(request).execute().body?.string()
}
}

withContext()可以切换到指定的线程,然后在闭包内的逻辑结束后,再切换到原来的线程继续执行。

Dispatchers

2020-03-21 22:09:50