kotlin - 更改 LiveData 的源流

标签 kotlin android-livedata kotlin-flow

我尝试在存储库中使用 Flow 而不是 LiveData。 在 View 模型中:

val state: LiveData<StateModel> = stateRepo
.getStateFlow("euro")
.catch {}
.asLiveData()

存储库:

 override fun getStateFlow(currencyCode: String): Flow<StateModel> {
    return serieDao.getStateFlow(currencyCode).map {with(stateMapper) { it.fromEntityToDomain() } }
 }

如果 currCode 在 vi​​ewModel 的生命周期内始终相同,则效果很好,例如 euro 但是如果 currCode 更改为 dollar 该怎么办?

如何使state显示另一个参数的Flow

最佳答案

您需要switchMap您的存储库调用。

我想你可以做这样的事情:

class SomeViewModel : ViewModel() {

    private val currencyFlow = MutableStateFlow("euro");

    val state = currencyFlow.switchMap { currentCurrency ->
        // In case they return different types
        when (currentCurrency) {
            // Assuming all of these database calls return a Flow
            "euro" -> someDao.euroCall()
            "dollar" -> someDao.dollarCall()
            else -> someDao.elseCall()
        }
        // OR in your case just call
        serieDao.getStateFlow(currencyCode).map {
            with(stateMapper) { it.fromEntityToDomain() }
        }
    }
    .asLiveData(Dispatchers.IO); //Runs on IO coroutines


    fun setCurrency(newCurrency: String) {
        // Whenever the currency changes, then the state will emit
        // a new value and call the database with the new operation
        // based on the neww currency you have selected
        currencyFlow.value = newCurrency
    }
}

关于kotlin - 更改 LiveData 的源流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65467364/

相关文章:

android - Kotlin 协程异步延迟

androidx 数据绑定(bind)生命周期 NullPointerException

android - 在Android MVVM中,需要多少个存储库和网络客户端来提供不同的查询?

android - Kotlin Flow - 有没有类似于 LiveData 的 emitSource 的东西?

android - 在 Android OpenGL ES 上只能看到没有几何图形的 glClear 颜色

kotlin - 来自不同类的调用扩展功能

swift - Kotlin 是否有像 Swift 那样的接口(interface)扩展类

java - 将通话与房间同步

android - Kotlin 协程 Flow 中 RxJava Observable 和 FlatMap 的等价物是什么

android - 将 pagingData 3 流与另一个流相结合