1. Background work & concurrency (using Schedulers)

A common requirement is to offload lengthy heavy I/O intensive operations to a background thread (non-UI thread) and feed the results back to the UI/main thread, on completion. This is a demo of how long-running operations can be offloaded to a background thread. After the operation is done, we resume back on the main thread. All using RxJava! Think of this as a replacement to AsyncTasks.

The long operation is simulated by a blocking Thread.sleep call (since this is done in a background thread, our UI is never interrupted).

To really see this example shine. Hit the button multiple times and see how the button click (which is a UI operation) is never blocked because the long operation only runs in the background.

2. Accumulate calls (using buffer)

This is a demo of how events can be accumulated using the "buffer" operation.

A button is provided and we accumulate the number of clicks on that button, over a span of time and then spit out the final results.

If you hit the button once, you'll get a message saying the button was hit once. If you hit it 5 times continuously within a span of 2 seconds, then you get a single log, saying you hit that button 5 times (vs 5 individual logs saying "Button hit once").

Note:

If you're looking for a more foolproof solution that accumulates "continuous" taps vs just the number of taps within a time span, look at theEventBus Demowhere a combo of thepublishandbufferoperators is used. For a more detailed explanation, you can also have a look at thisblog post.

3. Two-way data binding for TextViews (using PublishSubject)

Auto-updating views are a pretty cool thing. If you've dealt with Angular JS before, they have a pretty nifty concept called "two-way data binding", so when an HTML element is bound to a model/entity object, it constantly "listens" to changes on that entity and auto-updates its state based on the model. Using the technique in this example, you could potentially use a pattern like thePresentation View Model patternwith great ease.

While the example here is pretty rudimentary, the technique used to achieve the double binding using aPublish Subjectis much more interesting.

4. Simple and Advanced polling (using interval and repeatWhen)

This is an example of polling using RxJava Schedulers. This is useful in cases, where you want to constantly poll a server and possibly get new data. The network call is "simulated" so it forces a delay before return a resultant string.

There are two variants for this:

  1. Simple Polling: say when you want to execute a certain task every 5 seconds
  2. Increasing Delayed Polling: say when you want to execute a task first in 1 second, then in 2 seconds, then 3 and so on.

The second example is basically a variant ofExponential Backoff.

Instead of using a RetryWithDelay, we use a RepeatWithDelay here. To understand the difference between Retry(When) and Repeat(When) I wouuld suggest Dan'sfantastic post on the subject.

An alternative approach to delayed polling without the use ofrepeatWhenwould be using chained nested delay observables. SeestartExecutingWithExponentialBackoffDelay in the ExponentialBackOffFragment example.

5. Form validation (using.combineLatest)

Thanks to Dan Lew for giving me this idea in thefragmented podcast - episode #4(around the 4:30 mark).

.combineLatestallows you to monitor the state of multiple observables at once compactly at a single location. The example demonstrated shows how you can use.combineLatestto validate a basic form. There are 3 primary inputs for this form to be considered "valid" (an email, a password and a number). The form will turn valid (the text below turns blue :P) once all the inputs are valid. If they are not, an error is shown against the invalid inputs.

We have 3 independent observables that track the text/input changes for each of the form fields (RxAndroid'sWidgetObservablecomes in handy to monitor the text changes). After an event change is noticed fromall3 inputs, the result is "combined" and the form is evaluated for validity.

Note that theFunc3function that checks for validity, kicks in only after ALL 3 inputs have received a text change event.

The value of this technique becomes more apparent when you have more number of input fields in a form. Handling it otherwise with a bunch of booleans makes the code cluttered and kind of difficult to follow. But using.combineLatestall that logic is concentrated in a nice compact block of code (I still use booleans but that was to make the example more readable).

6. Simple timing demos (using timer, interval and delay)

This is a super simple and straightforward example which shows you how to use RxJava'stimer,intervalanddelayoperators to handle a bunch of cases where you want to run a task at specific intervals. Basically say NO to AndroidTimerTasks.

Cases demonstrated here:

  1. run a single task after a delay of 2s, then complete
  2. run a task constantly every 1s (there's a delay of 1s before the first task fires off)
  3. run a task constantly every 1s (same as above but there's no delay before the first task fires off)
  4. run a task constantly every 3s, but after running it 5 times, terminate automatically
  5. run a task A, pause for sometime, then execute Task B, then terminate

7. Simple Timeout example (using timeout)

This is a simple example demonstrating the use of the.timeoutoperator. Button 1 will complete the task before the timeout constraint, while Button 2 will force a timeout error.

Notice how we can provide a custom Observable that indicates how to react under a timeout Exception.

results matching ""

    No results matching ""