Observable でスケジューラを使用する
RxJava を使用している場合は、Observables に Scheduler を処理させる必要があると思います。私のコードでは、自分のワーカーを作成して管理する必要はなかったと思います。
スケジューラで Observable を使用し、2 つのスレッド タイプを切り替える例。
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());