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

结论

  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))