【问题标题】:How do I listen to DataStore changes in ViewModel?如何收听 ViewModel 中的 DataStore 更改?
【发布时间】:2021-06-20 10:38:07
【问题描述】:

所以我正在做一个应用程序,如果用户选择不同的位置,api 的查询也应该立即改变并返回新数据?

如何在视图模型中实现流观察器?

    val cityName: String = settingsManager.cityName.first()
    val countryName: String = settingsManager.countryName.first()
    val response: Response<AladhanApiResponse> = repo.getAdhanTime(cityName, countryName)

【问题讨论】:

  • 分享更多代码,你在哪里使用数据存储? cityName 的类型是什么?

标签: android kotlin mvvm kotlin-flow android-jetpack-datastore


【解决方案1】:

您可以使用combine operator 根据其他字段的更改创建响应流。但是,您的其他字段(cityName、countryName)也必须是流。您可以使用 MutableStateFlow 或其他一些逻辑在您的 settingsManager 中创建它们。

以下是创建响应流的方法,该响应流会在位置更改时自动更改:

val cityNameFlow = flowOf("London", "Barcelona").onEach { delay(100) } // Replace with flow of your cityName from settings
val countryName = flowOf("UK", "Spain").onEach { delay(150) } // Replace with flow of your countryName from settings

val responseFlow = combine(cityNameFlow, countryNameFlow) { cityName, countryName ->
    getAdhanTime(cityName, countryName)
}

responseFlow.collect { response ->
     // Called whenever new response is available (cityNameFlow or countryNameFlow changes) 
     println(response) 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2013-12-15
    • 2016-02-12
    • 2012-06-01
    • 2021-04-26
    相关资源
    最近更新 更多