0

I have an empty list as initial value to show skeleton loadings on recyclerview but the problem is the initial value doesn't get emmited when collected inside fragment and only receive the second value emitted from ViewModel after loading data.

ViewModel:

private val _orderHistoryList = MutableStateFlow(
    PagingData.from(Array(6) { OrderDetail(id = - 1L * it) }.toMutableList())
)
val orderHistoryList: StateFlow<PagingData<OrderDetail>> = _orderHistoryList

init {
    viewModelScope.launch {
        getOrderHistory.execute()
            .cachedIn(viewModelScope)
            .collect {
                _orderHistoryList.value = it
            }
    }
}

Fragment:

lifecycleScope.launch {
        repeatOnLifecycle(Lifecycle.State.STARTED) {
            viewModel.orderHistoryList.collect {
                adapter.submit(it)
            }
        }
    }
General Grievance
  • 4,555
  • 31
  • 31
  • 45

2 Answers2

0

You can use the stateIn operator to cache the initial value of the _orderHistoryList state flow and expose it as a StateFlow. Here's how:

val orderHistoryList: StateFlow<PagingData<OrderDetail>> = _orderHistoryList
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(), _orderHistoryList.value)
0

Use the onStart operator to emit an initial value when the flow collection starts.

getOrderHistory.execute()
    .onStart { emit( initialValue ) }
    .collect { ... }
Atick Faisal
  • 1,086
  • 1
  • 6
  • 13