问题描述
所以我有这个功能,我可以用流发送值,但我需要定期发送值,所以我使用了:
fun hereIsAFunction(): Flow<Type> = flow {
Handler.postDelayed({
//This is in Runnable and I can't emit values
emit(value) //Error 'Suspension function can only be called within Coroutine body
},1000)
usingOtherFunction()
}
我不想阻塞函数“usingOtherFunction()”,这就是我使用可运行函数的原因
问题: 有没有办法用 Flow 定期发送值?如果是,我应该调查什么?
解决方法
流程建立在协程之上。您可以使用协程的 delay(time)
方法来延迟执行。
此处有更多详细信息:https://developer.android.com/kotlin/flow#create
,根据您的评论,您要并行执行某些操作,可以在一个范围内启动 2 个协程。它们将彼此独立运行:
fun hereIsAFunction(): Flow<Type> = flow {
coroutineScope {
launch {
(0..100).forEach {
delay(1000)
emit(...)
}
}
launch {
usingOtherFunction()
}
}
}