Showing a simple Toast notification is a much less involved process than handling state screens. Toast notification provides a very quick and snappy way of informing a user about certain events in the system.
We will use Toast notification to notify a user that the data couldn't be loaded from the Internet, but we will fall back to the saved data that's in the database--the offline mode.
Let's take a look at how that can be incorporated in the current flow:
Observable.interval(0, 5, TimeUnit.SECONDS)
.flatMap(
i -> Observable.<YahooStockResult>error(new RuntimeException("Oops"))
)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(error -> {
log("doOnError", "error");
Toast.makeText(this, "We couldn't reach internet - falling
back to local data",
Toast.LENGTH_SHORT)
.show();
})
.observeOn(Schedulers.io())
.map(r -> r.getQuery().getResults().getQuote())
.flatMap(Observable::fromIterable)
.map(StockUpdate::create)
.doOnNext(this::saveStockUpdate)
.observeOn(AndroidSchedulers.mainThread())
A few things need special attention here. The following line produces the error that we will use to test our Toast notification:
i -> Observable.<YahooStockResult>error(new RuntimeException("Oops"))
Actual creation of Toast notification happens in the following block:
.observeOn(AndroidSchedulers.mainThread())
.doOnError(error -> {
Toast.makeText(this, "We couldn't reach internet - falling
back to local data",
Toast.LENGTH_SHORT)
.show();
})
Note that we have a call to .observeOn(AndroidSchedulers.mainThread()), which makes the next block execute on the main Android thread. This is necessary because Toast notification can be displayed only on the main Android thread.
In the following sections, somewhere down the flow, we will have a call to .onExceptionResumeNext() that will let us feed the flow with some backup Observable.