Last active
March 13, 2020 16:24
-
-
Save gpeal/145202421a4e6a1e79c6afeb58b50134 to your computer and use it in GitHub Desktop.
Fetching data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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