结论
- flowOn操作符对上游范围有效, 范围是指两个flowOn之间, 如果只有一个flowOn,则上游全部有效
- 最后一个flowOn后的操作所在线程与当前整个flow所在的线程池相同
日志
- 协程在IO线程
lifecycleScope.launch(Dispatchers.IO) {
flow {
Log.d("TAGTAG", "emit ${Thread.currentThread().name}")
emit(1)
}
.onStart {
Log.d("TAGTAG", "onStart ${Thread.currentThread().name}")
}
.flowOn(Dispatchers.Main)
.onEach {
Log.d("TAGTAG", "onEach ${Thread.currentThread().name}")
}
.flowOn(Dispatchers.IO)
.onCompletion {
Log.d("TAGTAG", "onCompletion ${Thread.currentThread().name}")
}
.collect {
Log.d("TAGTAG", "collect ${Thread.currentThread().name}")
}
}
image.png
- 协程在main线程
lifecycleScope.launch(Dispatchers.Main) {
flow {
Log.d("TAGTAG", "emit ${Thread.currentThread().name}")
emit(1)
}
.onStart {
Log.d("TAGTAG", "onStart ${Thread.currentThread().name}")
}
.flowOn(Dispatchers.Main)
.onEach {
Log.d("TAGTAG", "onEach ${Thread.currentThread().name}")
}
.flowOn(Dispatchers.IO)
.onCompletion {
Log.d("TAGTAG", "onCompletion ${Thread.currentThread().name}")
}
.collect {
Log.d("TAGTAG", "collect ${Thread.currentThread().name}")
}
}
image.png
网友评论