Skip to content

Instantly share code, notes, and snippets.

@gpeal
Last active March 13, 2020 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpeal/145202421a4e6a1e79c6afeb58b50134 to your computer and use it in GitHub Desktop.
Save gpeal/145202421a4e6a1e79c6afeb58b50134 to your computer and use it in GitHub Desktop.
Fetching data
data class MyState(
/** Use this to render the UI */
val fetchedGroups: List<Whatever> = emptyList()
/** Use this to show loading state/errors */
val groupsRequest: Async<Unit> = Uninitialized
) : MvRxState
class MyViewModel(initialState: MyState) : MvRxViewModel<MyState>(initialState) {
init {
fetchGroups()
}
fun fetchGroups() {
someObservable.execute { copy(groups = it.map { Unit }, fetchedGroups = it() ?: fetchedGroups) }
}
private fun <T, V> Async<T>.map(mapper: (T) -> V) = when (this) {
Uninitialized -> Uninitialized
is Loading -> Loading()
is Success -> Success(mapper(this()))
is Fail -> Fail(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment