Reactive Programming with Rxjava-Chapter7:Testing and Troubleshooting(2)

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 external = //...

Timer timer = metricRegistry.timer("timer");

Observable externalWithTimer = Observable
        .defer(() ->Observable.just(timer.time()))
        .flatMap(timerCtx ->
                external.doOnCompleted(timerCtx::stop));

你可能感兴趣的:(RxJava,1.x,学习笔记)