Last active
May 9, 2018 17:41
-
-
Save A-Zaiats/5577863138a4b9d972d15239ab4a0101 to your computer and use it in GitHub Desktop.
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
import org.junit.rules.TestRule; | |
import org.junit.runner.Description; | |
import org.junit.runners.model.Statement; | |
import java.util.concurrent.Callable; | |
import io.reactivex.Scheduler; | |
import io.reactivex.android.plugins.RxAndroidPlugins; | |
import io.reactivex.annotations.NonNull; | |
import io.reactivex.functions.Function; | |
import io.reactivex.plugins.RxJavaPlugins; | |
import io.reactivex.schedulers.Schedulers; | |
public class RxJunitRule implements TestRule { | |
private final Function<Scheduler, Scheduler> handler = new Function<Scheduler, Scheduler>() { | |
@Override | |
public Scheduler apply(@NonNull Scheduler scheduler) throws Exception { | |
return Schedulers.trampoline(); | |
} | |
}; | |
private final Function<Callable<Scheduler>, Scheduler> androidInitHandler = new Function<Callable<Scheduler>, Scheduler>() { | |
@Override | |
public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { | |
return Schedulers.trampoline(); | |
} | |
}; | |
@Override | |
public Statement apply(final Statement base, Description description) { | |
return new Statement() { | |
@Override | |
public void evaluate() throws Throwable { | |
clearHooks(); | |
applyTestHooks(); | |
base.evaluate(); | |
clearHooks(); | |
} | |
}; | |
} | |
private void clearHooks() { | |
RxJavaPlugins.reset(); | |
RxAndroidPlugins.reset(); | |
} | |
private void applyTestHooks() { | |
RxJavaPlugins.setComputationSchedulerHandler(handler); | |
RxJavaPlugins.setIoSchedulerHandler(handler); | |
RxJavaPlugins.setNewThreadSchedulerHandler(handler); | |
RxAndroidPlugins.setMainThreadSchedulerHandler(handler); | |
RxAndroidPlugins.setInitMainThreadSchedulerHandler(androidInitHandler); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment