Some loose notes about what I learned about ReactiveX and RxJava while developing Vitamin-Rx, a simplified clone of Vitamin-R 2.
Hot and cold Observables
When creating an Interval Observable, I thought it will start ticking (emitting) immediately after creation. Wrong! There are hot and cold Observables. Hot Observables start firing events immediately. Cold Observables, only when there is at least one subscriber. Interval is cold – you have to connect an Observer first.
Operators
Docs and marble diagrams are the best source of information about transforming Observables.
Pure streams and side effects
When you connect an Observer to an Observable, every item emitted by the source is passed to the onNext
Observer method. There are no restrictions on what you can put in the onNext
handler. On the other hand, there are do callbacks, which can act similarly to onNext
.
What’s the best practice? Implement onNext
handlers as pure functions. Actions with side-effects go into doOnNext
callbacks.
In my pet project, TimeSlice
class creates a tick stream transformed previously with pure functions. Main
class adds impure console and Growl notifications to the stream in do
callbacks. In this way I can unit test the Observable produced by the TimeSlice
class using the provided TestScheduler
(more on this in the next section).
Testing
Want to be a master of time? Test your Observables with TestScheduler
. You will be able to advance time and gather all items produced by the Observable under test. Check the TimeSliceTest
class for usage examples.
Backpressure
Backpressure is a way to deal with an Observable that produces items too rapidly (or too slowly).
In my case I wanted to pause the interval Observable and resume its activity. I didn’t find a direct way (i.e. through any of RxJava interfaces), so I asked on Stack Overflow. The solution consists in filtering the Observable by a boolean “semaphore” toggled from outside.