https://kotlinlang.org logo
Title
l

liminal

07/07/2022, 5:49 PM
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

uli

07/07/2022, 8:34 PM
l

liminal

07/08/2022, 1:44 PM
@uli thanks a lot. Looks like a great answer to me!
👍 1
Will try your suggestions out in the next couple of days
u

uli

07/08/2022, 1:53 PM
in our projects, we put the state handling into the repository and have a helper along those lines:
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:
val topRatedMoviesDataState : DataState<List<Movie>>
suspend fun loadTopRatedMovies() {
  loadData(topRatedMoviesDataState, ::loadTopRatedMoviesFromNetwork)
}
And your ViewModel would just subscribe to topRatedMoviesDataState.
👍 1
:thank-you: 1