Testing and Debugging
Virtual Time
Schedulers in Unit Testing
TestScheduler has two intriguing methods:advanceTimeBy() and advanceTimeTo() ,they are capable of advancing the time manually;otherwise,it`s frozen forever.
As you can see,TestScheduler is actually much more clever than an ordinary fake Clock abstraction.Not only do we have full control over current time,but we can also arbitrarily postpone all events. One caveat is that you must pass TestSchedule*r everywhere,basically to every operator that has an optional *Scheduler argument….From a testability point of view,you should prefer passing an explicit Scheduler.Moreover,consider dependency injection and provide *Scheduler*s from the outside.
Monitoring and Debugging
Every Observable has a set of callback methods that you can use to peek into various events,namely:
- doOnCompleted
- doOnEach()
- doOnError()
- doOnNext()
- doOnRequest()
- doOnSubscribe()
- doOnTerminate()
- doOnUnSubscribe()
Measuring and Monitoring
observable
.flatMap(x ->
makeNetworkCall(x)
.doOnSubscribe(counter::inc)
.doOnTerminate(counter::dec)
)
.subscribe( ... );
Observable<Long> external = //...
Timer timer = metricRegistry.timer("timer");
Observable<Long> externalWithTimer = Observable
.defer(() ->Observable.just(timer.time()))
.flatMap(timerCtx ->
external.doOnCompleted(timerCtx::stop));