简体   繁体   English

如何使用 Jetpack Compose 根据参数(对列表排序)在 StateFlow 中获取更新的结果

[英]How to get updated results in StateFlow depending on parameter (sorting a list) with Jetpack Compose

I made a state with StateFlow with 2 lists.我制作了带有 StateFlow 的 state 和 2 个列表。 This is working good.这工作得很好。 I want to sort these lists according to a parameter that user will decide how to sort.我想根据用户将决定如何排序的参数对这些列表进行排序。 This is my code in ViewModel:这是我在 ViewModel 中的代码:

@HiltViewModel
class SubscriptionsViewModel @Inject constructor(
    subscriptionsRepository: SubscriptionsRepository
) : ViewModel() {    
private val _sortState = MutableStateFlow(
    SortSubsType.ByDate
)
val sortState: StateFlow<SortSubsType> = _sortState.asStateFlow()

val uiState: StateFlow<SubscriptionsUiState> = combine(
    subscriptionsRepository.getActiveSubscriptionsStream(_sortState.value),
    subscriptionsRepository.getArchivedSubscriptionsStream(_sortState.value)
) { activeSubscriptions, archiveSubscriptions ->

    SubscriptionsUiState.Subscriptions(
        activeSubscriptions = activeSubscriptions,
        archiveSubscriptions = archiveSubscriptions,
    )
}
    .stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5_000),
        initialValue = SubscriptionsUiState.Loading
    )

fun sortSubscriptions(sortType: SortSubsType) {
    _sortState.value = sortType
}
}
sealed interface SubscriptionsUiState {
    object Loading : SubscriptionsUiState

    data class Subscriptions(
        val activeSubscriptions: List<Subscription>,
        val archiveSubscriptions: List<Subscription>,
    ) : SubscriptionsUiState

    object Empty : SubscriptionsUiState
}

sortSubscriptions - is the function called from @Composable screen. sortSubscriptions - 是从@Composable 屏幕调用的 function。 Like this:像这样:

  fun sortSubscriptions() {
        viewModel.sortSubscriptions(sortType = selectedSortType.asSortSubsType())
        isSortDialogVisible = false
    }

Without the sort function, everything works.没有排序 function,一切正常。 My question is how to fix this code so that the state changes when the sortState is changed.我的问题是如何修复此代码,以便 state 在 sortState 更改时更改。 This is my first try working with StateFlow.这是我第一次尝试使用 StateFlow。

The problem is that when you create your uiState flow with combine, you just use the current value of sortState and never react to its changes.问题在于,当您使用 combine 创建 uiState 流时,您只需使用 sortState 的当前值,而不会对其更改做出反应。

You need something like this:你需要这样的东西:

val uiState = sortState.flatMapLatest { sortValue ->
    combine(
        getActiveSubscriptionsStream(sortValue),
        getArchivedSubscriptionsStream(sortValue)
    ) { ... }
}.stateIn(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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