使用带有 Observable 的调度器
如果您使用的是 RxJava,我认为您应该让 Observables 处理调度程序。在我的代码中,我认为我不必创建自己的工人并管理它。
将 Observable 与调度程序一起使用并在两种线程类型之间切换的示例。
public void doSomething() {
Observable
.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Void> subscriber) {
int sleepTime = (int) (Math.random() * 10000);
System.out.println("Running on: " + Thread.currentThread().getId() + " sleep: " + sleepTime);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.out.println("Error!!! " + Thread.currentThread().getId());
subscriber.onError(e);
return;
}
System.out.println("Done!!! " + Thread.currentThread().getId());
subscriber.onNext(true);
subscriber.onCompleted();
}
})
// this will schedule your work in a background io thread. In this example the "call" method above.
.subscribeOn(Schedulers.io())
// this will schedule your next/complete/error on the androids main thread.
.observeOn(AndroidSchedulers.mainThread())
// kick off the actual work.
.subscribe(new Subscriber<Boolean>() {
@Override
public void onCompleted() {
// runs in main thread.
}
@Override
public void onError(Throwable e) {
// runs in main thread.
}
@Override
public void onNext(Boolean result) {
// runs in main thread.
}
});
}
直接使用调度器
但是,我确实了解可能存在需要您直接使用调度程序的情况。所以,如果你想直接使用调度器。我认为以下内容符合您的要求。
使用 runAction 创建调度程序实用程序。
public static void runAction(Action0 action, Scheduler scheduler) {
Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(new Action0() {
@Override
public void call() {
action.call();
worker.unsubscribe();
}
});
}
然后使用它,传递一个要执行的动作和要使用的调度程序。
SchedulerUtil.runAction(new Action0() {
@Override
public void call() {
int sleepTime = (int) (Math.random() * 10000);
System.out.println("Running on: " + Thread.currentThread().getId() + " sleep: " + sleepTime);
try {
Thread.sleep(sleepTime);
} catch (InterruptedException ignored) {
}
System.out.println("Done!!! " + Thread.currentThread().getId());
}
}, Schedulers.io());