我想给你一个关于延续概念的简单例子。这是暂停功能的作用,它可以冻结/暂停,然后继续/继续。停止在线程和信号量方面考虑协程。从连续性甚至回调挂钩的角度考虑它。
为了清楚起见,可以使用suspend
函数暂停协程。让我们调查一下:
在android中,我们可以例如这样做:
var TAG = "myTAG:"
fun myMethod() { // function A in image
viewModelScope.launch(Dispatchers.Default) {
for (i in 10..15) {
if (i == 10) { //on first iteration, we will completely FREEZE this coroutine (just for loop here gets 'suspended`)
println("$TAG im a tired coroutine - let someone else print the numbers async. i'll suspend until your done")
freezePleaseIAmDoingHeavyWork()
} else
println("$TAG $i")
}
}
//this area is not suspended, you can continue doing work
}
suspend fun freezePleaseIAmDoingHeavyWork() { // function B in image
withContext(Dispatchers.Default) {
async {
//pretend this is a big network call
for (i in 1..10) {
println("$TAG $i")
delay(1_000)//delay pauses coroutine, NOT the thread. use Thread.sleep if you want to pause a thread.
}
println("$TAG phwww finished printing those numbers async now im tired, thank you for freezing, you may resume")
}
}
}
上面的代码显示以下内容:
I: myTAG: my coroutine is frozen but i can carry on to do other things
I: myTAG: im a tired coroutine - let someone else print the numbers async. i'll suspend until your done
I: myTAG: 1
I: myTAG: 2
I: myTAG: 3
I: myTAG: 4
I: myTAG: 5
I: myTAG: 6
I: myTAG: 7
I: myTAG: 8
I: myTAG: 9
I: myTAG: 10
I: myTAG: phwww finished printing those numbers async now im tired, thank you for freezing, you may resume
I: myTAG: 11
I: myTAG: 12
I: myTAG: 13
I: myTAG: 14
I: myTAG: 15
想象它像这样工作:
因此,您从中启动的当前功能不会停止,只有协程会在继续运行时暂停。通过运行暂停功能不会暂停线程。
我认为该站点可以帮助您解决问题,是我的参考。
让我们做一些很酷的事情,并在迭代过程中冻结我们的暂停函数。我们将在稍后恢复onResume
存储一个名为的变量continuation
,我们将为它加载协程延续对象:
var continuation: CancellableContinuation<String>? = null
suspend fun freezeHere() = suspendCancellableCoroutine<String> {
continuation = it
}
fun unFreeze() {
continuation?.resume("im resuming") {}
}
现在,让我们返回暂停的函数,并使其在迭代过程中冻结:
suspend fun freezePleaseIAmDoingHeavyWork() {
withContext(Dispatchers.Default) {
async {
//pretend this is a big network call
for (i in 1..10) {
println("$TAG $i")
delay(1_000)
if(i == 3)
freezeHere() //dead pause, do not go any further
}
}
}
}
然后在onResume中的其他地方(例如):
override fun onResume() {
super.onResume()
unFreeze()
}
并且循环将继续。很高兴知道我们可以随时冻结一个悬浮函数,并在经过一段时间后恢复它。您也可以调查频道