将LiveData转换为StateFlow/SharedFlow

5

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

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

基本上,我想监听每个查询更改,以便根据情况返回内容。 因此,任何使用StateFlow / SharedFlow类似的东西都可以。

2个回答

2

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

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)

-2

switchMapflows 中已经被弃用,应该使用 flatMaptransformtransformLatest 之一来将一种类型的流转换为另一种。例如:

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

我想你可以用同样的逻辑来处理 StateFlow 或者 SharedFlows


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接