让我们考虑一下这种情况。我们有一些类,它有一个返回某个值的方法:
public class Foo() {
Observer<File> fileObserver;
Observable<File> fileObservable;
Subscription subscription;
public File getMeThatThing(String id) {
// implement logic in Observable<File> and return value which was
// emitted in onNext(File)
}
}
如何返回收到的值onNext
?正确的做法是什么?谢谢。
首先你需要更好地理解 RxJava,什么是 Observable -> Push 模型。这是解决方案供参考:
public class Foo {
public static Observable<File> getMeThatThing(final String id) {
return Observable.defer(() => {
try {
return Observable.just(getFile(id));
} catch (WhateverException e) {
return Observable.error(e);
}
});
}
}
//somewhere in the app
public void doingThings(){
...
// Synchronous
Foo.getMeThatThing(5)
.subscribe(new OnSubscribed<File>(){
public void onNext(File file){ // your file }
public void onComplete(){ }
public void onError(Throwable t){ // error cases }
});
// Asynchronous, each observable subscription does the whole operation from scratch
Foo.getMeThatThing("5")
.subscribeOn(Schedulers.newThread())
.subscribe(new OnSubscribed<File>(){
public void onNext(File file){ // your file }
public void onComplete(){ }
public void onError(Throwable t){ // error cases }
});
// Synchronous and Blocking, will run the operation on another thread while the current one is stopped waiting.
// WARNING, DANGER, NEVER DO IN MAIN/UI THREAD OR YOU MAY FREEZE YOUR APP
File file =
Foo.getMeThatThing("5")
.subscribeOn(Schedulers.newThread())
.toBlocking().first();
....
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)