https://kotlinlang.org logo
#rx
Title
n

nicka

02/18/2019, 11:05 PM
Hello all, I have a question about the best approach to handling conditional/if-else situation. I have an API response that will return one of three classes:
Loading
,
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
Copy code
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
Copy code
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) }
option two is nice because the side-effect is isolated into its own subscription. Also, I’ve heard in Rx you should be trying to avoid branching logic like whens/if-else etc but what’s preferrable?
g

ghedeon

02/19/2019, 12:11 AM
option 1 is much easier to read, tho, less noisy. Unrelated, but I've never understood why people use
loading
in result of the api call simple smile. Don't you always know that you're loading when you subsribe?
n

nicka

02/19/2019, 4:58 AM
I agree its easier to read; however what’s more consistent with sortof the “philosophy” of Rx? (also unfortunately the loading thing is outside of my control — agree its not great)
e

edwardwongtl

02/19/2019, 5:48 AM
The
Loading
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.
n

nicka

02/19/2019, 7:39 PM
@edwardwongtl any thoughts on the above two options?
tagging @ursus too because he seems active here
u

ursus

02/19/2019, 7:46 PM
2 could be dont without the share, with publish that takes a function
if youre gonna do just mapping then 1, but 2 gives you options to add different operators
per branch
e

edwardwongtl

02/20/2019, 3:28 AM
I would say I prefer 1
2 Views