简体   繁体   中英

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

 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.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:

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 :

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:

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 :

adapter.submitList(viewModel.getRtList())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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