Creating transformer classes

Sometimes, it is worthwhile to move the extracted transformer to its own class. In most cases, this will be code that can be reused in multiple places between multiple Observables. In this section, we will see how we can do that to the persistence code, and we will explore a few additional examples for file-based caching and measure the timing of the execution.

For starters, as an exercise, we will move the code that handles the persistence of StockUpdate items to a separate class.

First of all, let's create a Transformer class in packt.reactivestocks.storio :

package packt.reactivestocks.storio;

import io.reactivex.ObservableTransformer;
import packt.reactivestocks.StockUpdate;

public class
LocalItemPersistenceHandlingTransformer implements ObservableTransformer<StockUpdate, StockUpdate> {

}

Next, we will add the .apply() method that will execute the transformation itself:

public class LocalItemPersistenceHandlingTransformer implements ObservableTransformer<StockUpdate, StockUpdate> {

@Override
public ObservableSource<StockUpdate> apply(Observable<StockUpdate>
upstream) {
return upstream.doOnNext(this::saveStockUpdate)
.onExceptionResumeNext(StorIOFactory
.createLocalDbStockUpdateRetrievalObservable(context));
}
}

We will do this along with the saveStockUpdate() method from the MainActivity class where we had it before:

private void saveStockUpdate(StockUpdate stockUpdate) {
StorIOFactory.get(context)
.put()
.object(stockUpdate)
.prepare()
.asRxSingle()
.toBlocking()
.value();
}

As we can see, it requires a Context dependency, so we will have to pass it through a constructor to the Transformer, like this:

public class LocalItemPersistenceHandlingTransformer implements ObservableTransformer<StockUpdate, StockUpdate> {
private final Context context;

private
LocalItemPersistenceHandlingTransformer(Context context) {
this.context = context;
}
...
}

Finally, for the convenience, we will add a static Factory Method:

public static LocalItemPersistenceHandlingTransformer addLocalItemPersistenceHandling(Context context) {
return new LocalItemPersistenceHandlingTransformer(context);
}

This will let us be more flexible in the naming of the Transformer.

At the very last, find the relevant line in the main flow:

.compose(addLocalItemPersistenceHandling())

We need to change it to this:

.compose(addLocalItemPersistenceHandling(this))

However, do not forget to add a static import at the top:

import static packt.reactivestocks.storio.LocalItemPersistenceHandlingTransformer.*;

Next, we will explore examples for the file-based caching and the measuring of the execution time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.149.238