android StateFlow不发出初始值

xxhby3vn  于 2023-05-05  发布在  Android
关注(0)|答案(2)|浏览(181)

我有一个空的列表作为初始值来显示recyclerview上的 backbone 加载,但问题是当在片段内收集时,初始值不会被发送,并且在加载数据后只接收从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)
            }
        }
    }
r3i60tvu

r3i60tvu1#

使用onStart操作符在流收集开始时发出一个初始值。

getOrderHistory.execute()
    .onStart { emit( initialValue ) }
    .collect { ... }
wtzytmuj

wtzytmuj2#

您可以使用stateIn操作符来缓存_orderHistoryList状态流的初始值,并将其公开为StateFlow。具体操作如下:

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

相关问题