Currently, in our main Observable flow, there is a big chunk of code that is responsible for the retrieval of financial stock updates and tweets in case there was an exception in the upstream:
.onExceptionResumeNext(
v2(StorIOFactory.get(this)
.get()
.listOfObjects(StockUpdate.class)
.withQuery(Query.builder()
.table(StockUpdateTable.TABLE)
.orderBy("date DESC")
.limit(50)
.build())
.prepare()
.asRxObservable())
.take(1)
.flatMap(Observable::fromIterable)
)
As you remember, this is used to retrieve elements from the local database when there is no internet connectivity (or some other error occurred upstream).
This big piece of code is quite distracting and takes attention of the purpose it is supposed to complete in the flow, so it should be extracted into something more descriptive, such as the following:
.onExceptionResumeNext(createLocalDbStockUpdateRetrievalObservable())
Obviously, the createLocalDbStockUpdateRetrievalObservable() method contains the same functionality as before:
private Observable<StockUpdate> createLocalDbStockUpdateRetrievalObservable() {
return v2(StorIOFactory.get(this)
.get()
.listOfObjects(StockUpdate.class)
.withQuery(Query.builder()
.table(StockUpdateTable.TABLE)
.orderBy("date DESC")
.limit(50)
.build())
.prepare()
.asRxObservable())
.take(1)
.flatMap(Observable::fromIterable);
}
Since this creates a completely new and independent Observable, and it can be reused in multiple other places, it makes sense to move it to the StorIOFactory class from MainActivity where it was just extracted. This Factory Method will need a few slight modifications, as it can be seen here:
public static Observable<StockUpdate> createLocalDbStockUpdateRetrievalObservable(Context context) {
return v2(StorIOFactory.get(context)
.get()
.listOfObjects(StockUpdate.class)
.withQuery(Query.builder()
.table(StockUpdateTable.TABLE)
.orderBy("date DESC")
.limit(50)
.build())
.prepare()
.asRxObservable())
.take(1)
.flatMap(Observable::fromIterable);
}
private static <T> Observable<T> v2(rx.Observable<T> source) {
return toV2Observable(source);
}
Since StorIOFactory.get() requires the context from Android, we have to pass it as an argument. Now, the relevant part in MainActivity will become this:
.onExceptionResumeNext(StorIOFactory.createLocalDbStockUpdateRetrievalObservable(this))
By extracting a simple Factory Method, we basically simplified our existing flow by more than 10 lines, and we gave a name to properly describe what's happening. Now, the other developers (or future you) will have a much easier time wrapping their heads around to what the code does.