我有一个空列表作为初始值来显示 recyclerview 上的骨架加载,但问题是初始值在收集到片段内部时不会发出,并且只接收加载数据后从 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
}
}
}
片段:
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.orderHistoryList.collect {
adapter.submit(it)
}
}
}
您可以使用
stateIn
运算符来缓存_orderHistoryList 状态流的初始值并将其公开为StateFlow
。方法如下:
val orderHistoryList: StateFlow<PagingData<OrderDetail>> = _orderHistoryList
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), _orderHistoryList.value)
使用 onStart 运算符在流收集开始时发出初始值。
getOrderHistory.execute()
.onStart { emit( initialValue ) }
.collect { ... }