I am now implementing MutableStateFlow to store the cache value in Android MVVM architecture . The goal is, it could be fetched only at the first time to avoid much redundant network connection and it could be also updated when needed. Therefore, I have the following questions:
- How to reset the value and request fetch data again in the MutableStateFlow with the following code?
- Am I on a wrong track to use lazy to save the cache value?
class WeatherRepository {
private val mDefaultDispatcher: IDefaultDispatcher by inject()
private val scope by lazy { CoroutineScope(mDefaultDispatcher.io() + SupervisorJob()) }
val cacheWeather by lazy {
val flow = MutableStateFlow<List<Weather>?>(null)
scope.launch(mDefaultDispatcher.io()) {
val response = getWeather()
if (response.isValid) {
val data = response.data
flow.value = data
}
}
flow
}
}
class ViewModelA {
private val mRepository: WeatherRepository by inject()
val weather by lazy {
mRepository.cacheWeather.asLiveData()
}
fun requestUpdateOnWeather() {
//TODO (dunno how to make the mutableStateFlow reset and fetch data again)
}
}
class ViewModelB {
private val mRepository: WeatherRepository by inject()
val weather by lazy {
mRepository.cacheWeather.asLiveData()
}
}
Appreciate any comment or advice
