3

StateFlow / SharedFlow 中这种实时数据转换的等效代码是什么?

val myLiveData: LiveData<MyLiveData> = Transformations
                    .switchMap(_query) {
                        if (it == null) {
                           AbsentLiveData.create()
                        } else {
                           repository.load()
                     }

基本上,我想听每个查询更改以响应返回的内容。所以,任何类似于使用 StateFlow / SharedFlow 的东西都是受欢迎的。

4

2 回答 2

0

首先,创建一个辅助扩展函数:

fun <R> Flow<R>.toStateFlow(coroutineScope: CoroutineScope, initialValue: R) = stateIn(coroutineScope, SharingStarted.Lazily, initialValue)

用于:mapLatest{}_Transformations.map()

val studentNames = _students.mapLatest { students ->
    students.map { "${it.name}" }
}.toStateFlow(uiScope, emptyList())    //uiScope is viewModelScope

用于:flatMapLatest{}_Transformations.switchMap()

val asteroids = _asteroidFilter.flatMapLatest { filter ->
    asteroidRepository.getAsteroidsFlow(filter)
}.toStateFlow(uiScope, emptyList())

用于:combine()_MediatorLiveData

val sumScore = combine(_team1Score, _team2Score) { score1, score2 ->
    score1 + score2
}.toStateFlow(uiScope, 0)
于 2022-02-19T16:56:58.613 回答
-1

switchMap在 中已弃用,应flows使用或将一种类型的流转换为其他类型。一个例子是flatMaptransformtransformLatest

val myFlow = flowOf<Int>().transform<Int, String> { flowOf("$it") }} 

StateFlow我猜你可以对or使用相同的逻辑SharedFlows

于 2021-02-11T07:05:29.760 回答