我需要在非常慢的设备上模拟应用的行为。所以我想覆盖Schedulers.io()只使用一个低优先级的线程。并且,如果可能的话,在将任务排入队列之前添加一些延迟。有没有想法如何全局一次,没有更改Schedules.io()调用代码?
答案 0 :(得分:1)
您可以通过Schedulers.from(Executor)
打包单个线程执行程序,然后将生成的Scheduler
包装为另一个:
ExecutorService exec = Executors.newSingleThreadExecutor();
final Scheduler sch = Schedulers.from(exec);
final long delayMillis = 1000;
Scheduler newScheduler = new Scheduler() {
@Override public Worker createWorker() {
return new NewWorker(sch.createWorker());
}
class NewWorker extends Scheduler.Worker {
final Worker actual;
NewWorker(Worker actual) {
this.actual = actual;
}
@Override public void unsubscribe() {
actual.unsubscribe();
}
@Override public boolean isUnsubscribed() {
return actual.isUnsubscribed();
}
@Override public Subscription schedule(Action0 action) {
return actual.schedule(action, delayMillis, TimeUnit.MILLISECONDS);
}
@Override public Subscription schedule(Action0 action, long delayTime,
TimeUnit unit) {
return actual.schedule(action, delayTime, unit);
}
}
};
RxJavaHooks.setOnIOScheduler(original -> newScheduler);
Observable.just(1)
.observeOn(Schedulers.io())
.toBlocking()
.subscribe(System.out::println);
完成后,不要忘记关闭ExecutorService并重置挂钩:
exec.shutdown();
RxJavaHooks.setOnIOScheduler(null);