我需要在后台线程上执行一些工作,然后在主线程上传递结果。我做了以下事情:
Observable.just(new Object()).subscribeOn(Schedulers.newThread()).subscribeWith(new DisposableObserver<Object>() {
@Override
public void onNext(Object s) {
try {
doSomething()
Observable.just(new Object())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Object>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(Object o) {
completion.deliverResult()
onComplete();
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
} catch (DriverException e) {
badThingsHappened()
onError(e);
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
但是我不喜欢这段代码,它似乎很复杂,很多东西都没用过。
有没有办法让它更优雅?
答案 0 :(得分:2)
您的代码可以转换为与此类似的代码:
Observable
.create(emitter -> {
Result result;
try {
result = doSomething();
} catch (Exception error) {
emitter.onError(error);
return;
} finally {
if (result == null) {
emitter.onError(new IllegalStateException("Result cannot be null"));
return;
}
}
emitter.onNext(result);
emitter.onComplete();
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(result -> completion.deliverResult(result),
throwable -> badThingsHappened(throwable));
但是通过这种方法,您将传统的回调与反应式编程混合在一起:completion.deliverResult()
是一种标准的回调。而不是这样做,返回可观察流本身,让感兴趣的客户端观察流本身。
答案 1 :(得分:1)
你可以用几行代码做你想做的事。
在这个片段中,我从Callable创建了一个Observable对象。计算将在IO线程上完成,但结果(或最终错误)将在Android主线程上观察到
void execute() {
// here you get your observable (api, db, other repositories). I'll create a simple String observable
Observable<String> observable = Observable.fromCallable(
() -> "This method will be executed on IO Thread"
);
// here you create your observer. I'll observe a string, so I need a Observer<String> obj
Observer<String> stringObserver = new StringObserver();
//now the observable will do his job on IO thread, but the result is emitted on mainThread
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(stringObserver);
}
class StringObserver extends DisposableObserver<String> {
@Override
public void onNext(String s) {
//will be executed on main thread
}
@Override
public void onError(Throwable e) {
//will be executed on main thread
}
@Override
public void onComplete() {
//will be executed on main thread
}
}