-1

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)
        }
    }
    ```
Sergio
  • 27,326
  • 8
  • 128
  • 149
asqa
  • 199
  • 3
  • 17
  • What do you mean by "exit when executing this line"? Is it crashing? Are there any logs in the Logcat? Do you call somewhere `viewModel.getRtList()`? – Sergio Sep 11 '22 at 09:05
  • there is no error inside log, i mean will return when reach this line viewModel.rtList.collect{ list -> and won't to execute adapter.submitList(list) – asqa Sep 11 '22 at 09:24

1 Answers1

0

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())
Sergio
  • 27,326
  • 8
  • 128
  • 149