nicka
02/18/2019, 11:05 PMLoading
, Error
, or Finished
— all of which inherit from a class called: NetworkState
.
If its Loading or Error, I want to update my UI appropriately. If its finished, I need to extract the data, do further transformations, then update the UI. I also need to perform a side-effect depending on one of the values returned.
I can think of two ways to do this. Which of these is preferable? Is there a better third option?
OPTION 1
fetchFromApi().
.map {
when (it) {
is Loading -> transformToLoadingView()
is Error -> transformToErrorView()
is Finished -> mapDataToUI(it.data)
}.subscribe { view -> updateUi(view) }
fun mapDataToUI(data: Data) {
performSideEffect(data)
transformDataToView(data)
}
OPTION 2
val sharedResponse = fetchFromApi().share()
Observable.merge(
sharedResponse.ofType('Loading').map { loadingView },
sharedResponse.ofType('Error').map { errorView },
sharedResponse.ofType('Finished').map { transformDataToView(it) }
).subscribe { view -> updateUi(view) }
sharedResponse.ofType('Finished').subscribe { performSideEffect(it) }
ghedeon
02/19/2019, 12:11 AMloading
in result of the api call simple smile. Don't you always know that you're loading when you subsribe?nicka
02/19/2019, 4:58 AMedwardwongtl
02/19/2019, 5:48 AMLoading
State is just for keeping the whole application state inside the viewModel instead of letting the view to decide if it is loading or not.nicka
02/19/2019, 7:39 PMursus
02/19/2019, 7:46 PMedwardwongtl
02/20/2019, 3:28 AM