My stackoverflow question didn't get any traction ...
# coroutines
l
My stackoverflow question didn't get any traction so I am hoping that someone will help here https://stackoverflow.com/questions/72843100/kotlin-flow-emit-loading-state-for-every-emission
u
l
@uli thanks a lot. Looks like a great answer to me!
👍 1
Will try your suggestions out in the next couple of days
u
in our projects, we put the state handling into the repository and have a helper along those lines:
Copy code
suspend <T> fun loadData<T>(stateFlow: DataState, dataLoader: suspend () -> T) {
  try { 
    if (stateFlow.value == DataState.Loading) return
    stateFlow.value = DataState.Loading
    val result = dataLoader()
    stateFlow.value = DataState.Loaded(result)
  } catch (t: Throwable) {
    stateFlow.value = DataState.Error(t)
  }
}
Then your actual repository method would go like this:
Copy code
val topRatedMoviesDataState : DataState<List<Movie>>
suspend fun loadTopRatedMovies() {
  loadData(topRatedMoviesDataState, ::loadTopRatedMoviesFromNetwork)
}
And your ViewModel would just subscribe to topRatedMoviesDataState.
👍 1
🙏 1