美文网首页kotlinKotlin
kotlin flow切换线程操作(flow flowOn)

kotlin flow切换线程操作(flow flowOn)

作者: yin_xin | 来源:发表于2021-12-30 15:53 被阅读0次

    结论

    1. flowOn操作符对上游范围有效, 范围是指两个flowOn之间, 如果只有一个flowOn,则上游全部有效
    2. 最后一个flowOn后的操作所在线程与当前整个flow所在的线程池相同

    日志

    1. 协程在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
    1. 协程在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

    相关文章

      网友评论

        本文标题:kotlin flow切换线程操作(flow flowOn)

        本文链接:https://www.haomeiwen.com/subject/rtgiqrtx.html