简体   繁体   English

无法收集 kotlin 流量

[英]Cannot collect kotlin Flow

My code always exit when executing this line, actually i already use coroutine to execute the collector code, and already use updated library for coroutine also执行此行时我的代码总是退出,实际上我已经使用协程来执行收集器代码,并且也已经使用更新的协程库

viewModel.rtList.collect{ list ->
    adapter.submitList(list)
} 

and here is my full collector code这是我的完整收集器代码

 viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                Toast.makeText(requireContext(), "collect", Toast.LENGTH_SHORT).show()
                try {
                    viewModel.rtList.collect{ list ->
                        adapter.submitList(list)
                    }
                }catch (e:Exception){
                    Log.e(TAG, "initObserver: ${e.message}", )
                }
                
            }
        }

And here is in ViewModel这是在 ViewModel

 private var _rtList= MutableSharedFlow<List<DataRt>>()
 val rtList: SharedFlow<List<DataRt>> = _rtList

 fun getRtList() {
        viewModelScope.launch {
            val list = mutableListOf<DataRt>()
            for (rt in 1..12){
                val dataRt = DataRt(rt.toString(),"0")
                list.add(dataRt)
            }
            _rtList.emit(list)
        }
    }
    ```

Please make sure you start collecting the data before it has been emitted.请确保在数据发出之前开始收集数据。 For example call viewModel.getRtList() after launching a coroutine to collect the data:例如在启动协程后调用viewModel.getRtList()来收集数据:

viewModel.rtList.collect { list ->
    adapter.submitList(list)
} 

viewModel.getRtList()

Or in this case it would be better to use a flow{} builder to execute a block of code each time the Flow is being collected:或者在这种情况下,最好使用flow{}构建器在每次收集Flow时执行代码块:

ViewModel : ViewModel

fun getRtList() = flow {
    val list = mutableListOf<DataRt>()
    for (rt in 1..12){
        val dataRt = DataRt(rt.toString(),"0")
        list.add(dataRt)
    }
    emit(list)
}

Activity/Fragment : Activity/Fragment

viewModel.getRtList().collect{ list ->
    adapter.submitList(list)
} 

Or event better solution: don't use a Flow here, because you emit only one value and you don't call suspend functions:或者事件更好的解决方案:不要在这里使用Flow ,因为你只发出一个值并且你不调用suspend函数:

ViewModel : ViewModel

fun getRtList(): List<DataRt> {
    val list = mutableListOf<DataRt>()
    for (rt in 1..12){
        val dataRt = DataRt(rt.toString(),"0")
        list.add(dataRt)
    }
    return list
}

Activity/Fragment : Activity/Fragment

adapter.submitList(viewModel.getRtList())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM