If you are a mobile application developer, one situation you will commonly run into is loading and displaying data to a user. With that reality, there are almost always two caveats:

Data might take time to arrive, or It might fail to arrive due to unforeseen circumstances like a bad network connection

A common situation when using RxJava to load data

As long as data loading conditions are very simple, this is effective. But, what if the conditions defining the data can change and we need to reload the data? What if data is updated and we need to propagate that update? We can try to model it in an idiomatic way

There are a couple of issues here:

We lose the context of when the data is refreshing/loading Either we are not propagating errors or it will kill our stream

To solve this issue, let’s create an immutable value type that provides this context to us.

Let’s update our repository signature to

Now we can consume the data

Constructing Lce Observables

So far, I’ve only shown the stubbed version of Observable<Lce<Data>>. The reason is that it is an implementation detail. How you construct it will depend on your data requirements.

Here is how a simple single request implementation could look like when using a Retrofit api

If you want it to be refreshable

The view implementation doesn’t have to change much or at all to handle this change. We are hiding implementation details from the view layer while at the same time keeping the logic unit testable to ensure correct behavior.

Combining

Let’s say that the view requires data combined from two sources. We can easily compose these observables into a single stream

If something triggers user or content update, this stream will propagate the correct events down to the view. So if either the user or the content is loading, the view will show that.

Real world use case

On the Instacart consumer app, we require user data to be available before we make any subsequent API calls.

To display the store chooser, we need the list of stores. Stores depend on the zip code you are in. Every time the zip code changes, we need to refresh the stores.

Conclusion