Last active
August 14, 2017 10:14
-
-
Save Kursulla/46a4829da753fcbc09efe5b171663ed7 to your computer and use it in GitHub Desktop.
For testing, you have to "serialize threads" of RX. Regardless of Scheduler production code specifies, you have to execute that instantly. That is why we are using custom rule. In it we override any new schedulers with immediate one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.eutechpro; | |
import org.junit.rules.TestRule; | |
import org.junit.runner.Description; | |
import org.junit.runners.model.Statement; | |
import java.util.concurrent.TimeUnit; | |
import io.reactivex.Scheduler; | |
import io.reactivex.android.plugins.RxAndroidPlugins; | |
import io.reactivex.annotations.NonNull; | |
import io.reactivex.disposables.Disposable; | |
import io.reactivex.internal.schedulers.ExecutorScheduler; | |
import io.reactivex.plugins.RxJavaPlugins; | |
public class RxImmediateSchedulerRule implements TestRule { | |
private Scheduler immediate = new Scheduler() { | |
@Override | |
public Disposable scheduleDirect(@NonNull Runnable run, long delay, @NonNull TimeUnit unit) { | |
return super.scheduleDirect(run, 0, unit); | |
} | |
@Override | |
public Scheduler.Worker createWorker() { | |
return new ExecutorScheduler.ExecutorWorker(Runnable::run); | |
} | |
}; | |
@Override | |
public Statement apply(final Statement base, Description description) { | |
return new Statement() { | |
@Override | |
public void evaluate() throws Throwable { | |
RxJavaPlugins.setInitIoSchedulerHandler(scheduler -> immediate); | |
RxJavaPlugins.setInitComputationSchedulerHandler(scheduler -> immediate); | |
RxJavaPlugins.setInitNewThreadSchedulerHandler(scheduler -> immediate); | |
RxJavaPlugins.setInitSingleSchedulerHandler(scheduler -> immediate); | |
RxAndroidPlugins.setInitMainThreadSchedulerHandler(scheduler -> immediate); | |
try { | |
base.evaluate(); | |
} finally { | |
RxJavaPlugins.reset(); | |
RxAndroidPlugins.reset(); | |
} | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment