Rx java 在0.18中,后台任务如何在调度程序上执行?
感觉我在这里错过了一些东西,但在我过去常做的地方:Rx java 在0.18中,后台任务如何在调度程序上执行?,rx-java,Rx Java,感觉我在这里错过了一些东西,但在我过去常做的地方: Schedulers.io().schedule(new Action1<Scheduler.Inner>() { @Override public void call(Scheduler.Inner inner) { doWhatever(); } }); 但这似乎需要做更多的工作(特别是对于android.mainThread调度程序) 我在这里遗漏了什么?使
Schedulers.io().schedule(new Action1<Scheduler.Inner>() {
@Override
public void call(Scheduler.Inner inner) {
doWhatever();
}
});
但这似乎需要做更多的工作(特别是对于android.mainThread调度程序)
我在这里遗漏了什么?使用可观察的调度程序
如果您使用的是RxJava,我认为应该让Observable处理调度程序。在我的代码中,我不认为我必须创建自己的工作人员并对其进行管理
使用Observable with Scheduler并在两种线程类型之间切换的示例
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.
}
});
}
然后,要使用它,请传递要执行的操作和要使用的调度程序
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());
这里是讨论:我已经通读了那个讨论——我不确定你到底指的是什么,但我没有看到任何东西能给出一个例子来说明这个问题中表达的观点。你在这里具体想说什么?
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());