Home » Android » What does this RxJava test rule code block do?

What does this RxJava test rule code block do?

Posted by: admin November 1, 2017 Leave a comment

Questions:

I saw the below code block when I need to test some RxJava methods in unit tests. My understanding is you need to convert asynchronous calls to synchronous ones so it can be properly tested.

Can anyone explain what each below method does in detail?

private final Function<Callable<Scheduler>, Scheduler> mRxAndroidSchedulersHook =
        new Function<Callable<Scheduler>, Scheduler>() {
            @Override
            public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable)
                    throws Exception {
                return getScheduler();
            }
        };

private final Function<Scheduler, Scheduler> mRxJavaImmediateScheduler =
        new Function<Scheduler, Scheduler>() {
            @Override
            public Scheduler apply(@NonNull Scheduler scheduler) throws Exception {
                return getScheduler();
            }
        };

@Override
public Statement apply(final Statement base, Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            RxAndroidPlugins.reset();
            RxAndroidPlugins.setInitMainThreadSchedulerHandler(mRxAndroidSchedulersHook);

            RxJavaPlugins.reset();
            RxJavaPlugins.setIoSchedulerHandler(mRxJavaImmediateScheduler);
            RxJavaPlugins.setNewThreadSchedulerHandler(mRxJavaImmediateScheduler);

            base.evaluate();

            RxAndroidPlugins.reset();
            RxJavaPlugins.reset();
        }
    };
}

public Scheduler getScheduler() {
    return Schedulers.trampoline();
}
Answers: