Skip to content

Instantly share code, notes, and snippets.

@gokhanaliccii
Last active June 29, 2018 07:00
Show Gist options
  • Save gokhanaliccii/9a106f4465522b58a4537dd970a47f75 to your computer and use it in GitHub Desktop.
Save gokhanaliccii/9a106f4465522b58a4537dd970a47f75 to your computer and use it in GitHub Desktop.
Rx java test rule
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.functions.Function;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
public class RxJavaTestScheduler implements TestRule {
private Scheduler SCHEDULER_INSTANCE = Schedulers.trampoline();
private Function<Scheduler, Scheduler> schedulerFunction = scheduler -> SCHEDULER_INSTANCE;
private Function<Callable<Scheduler>, Scheduler> schedulerFunctionLazy = schedulerCallable -> SCHEDULER_INSTANCE;
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
RxAndroidPlugins.reset();
RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerFunctionLazy);
RxJavaPlugins.reset();
RxJavaPlugins.setIoSchedulerHandler(schedulerFunction);
RxJavaPlugins.setNewThreadSchedulerHandler(schedulerFunction);
RxJavaPlugins.setComputationSchedulerHandler(schedulerFunction);
base.evaluate();
RxAndroidPlugins.reset();
RxJavaPlugins.reset();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment