【问题标题】:Change source Flow for LiveData更改 LiveData 的源流
【发布时间】:2020-12-28 00:30:53
【问题描述】:

我尝试在 repos 中使用 Flow 而不是 LiveData。 在视图模型中:

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

【问题讨论】:

    标签: kotlin android-livedata kotlin-flow


    【解决方案1】:

    您需要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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-09
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      相关资源
      最近更新 更多