2015-06-20 181 views
8

我们来考虑一下这种情况。我们有一些类,它有一个方法,它返回某个值:如何使用RxJava返回值?

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收到了价值?什么是正确的方法?谢谢。

回答

24

您首先需要更好地理解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(); 
    .... 
} 
+0

谢谢。我刚开始试用RxJava。我处于这种情况,我的方法需要返回'File'而不是'Observable ',因为许多应用程序的其他部分正在请求'File'。这可能吗?等待,直到有结果,然后返回。 – user3339562

+1

RxJava的全部意义在于,将拉模型(现在让我这个)变成推模型(我在这里等待这个数据)。它需要重新考虑你做你的方法的方式。好处是推动模型是可组合的,单个错误处理和平滑操作是微不足道的。 –

+0

现在,除非您开始使用调度程序进行线程化和平滑化,否则一旦订阅命中,您的observables将同步执行操作。 –