2015-06-20 45 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將同步執行操作。 –