/**
* Does some work and return true to denote success
* false to denote failure
*/
suspend fun doWork(): Boolean {
val processStatus = processWork()
return processStatus.filter { status ->
status == ProcessStatus.SUCCESS
|| status == ProcessStatus.FAILURE
}.map { filteredStatus ->
filteredStatus == ProcessStatus.SUCCESS
}.single()
}
/**
* Cretaes a channel in which different status will be offered
*/
suspend fun processWork(): Flow<ProcessStatus> {
val channel = BroadcastChannel(Channel.BUFFERED)
doThework(channel)
return channel.asFlow()
}
/**
* Does some work in background thread
*/
fun doThework(channel: BroadcastChannel) {
SomeSope.launch {
//Cretae a coroutine
channel.offer(ProcessStatus.Status1)
channel.offer(ProcessStatus.Status2)
channel.offer(ProcessStatus.Status3)
channel.offer(ProcessStatus.Status4)
channel.offer(rocessStatus.SUCCESS)
channel.close()
}
}
以上是我的代码的简化版本。
我想要做的是,doWork()
等到所有值都被释放,最后返回一个基于 last ProcessStatus.SUCCESS
or的布尔值ProcessStatus.FAILURE
。
现在,上面的代码发生的事情是,一旦processWork()
返回流。doWork()
调用包括single()
and 在内的所有运算符,因为工作仍在进行中 ProcessStatus.FAILURE 或 ProcessStatus.SUCCESS 仍未发出,使其异常。
如何让doWork()
return 语句等待并仅在流程完成时返回?
编辑1:
原因,我必须使用频道是因为,这是 Android 代码的一部分,channel.offer()
实际上并不是像上面示例中那样的新协程,而是从 Android 调用BroadcastReceiver
。
由于流程很冷,我不希望用户离开活动来阻止任务完成和通知。