【问题标题】:How to return value with RxJava?如何使用 RxJava 返回值?
【发布时间】:2015-09-06 02:07:06
【问题描述】:

让我们考虑一下这种情况。我们有一些类有一个方法可以返回一些值:

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

【问题讨论】:

    标签: android rx-java


    【解决方案1】:

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

    【讨论】:

    • 谢谢。我刚开始尝试使用 RxJava。我的方法需要返回File 而不是Observable&lt;File&gt;,因为应用程序的许多其他部分都在请求File。那可能吗?等到有结果再返回。
    • RxJava 的全部意义在于,将拉模型(现在给我这个)转变为推模型(我在这里等待这个数据)。它需要重新思考你做你的方法的方式。好处是推送模型是可组合的、单一的错误处理和并行化操作是微不足道的。
    • 现在,除非您开始使用调度程序进行线程化和并行化,否则您的可观察对象将在订阅命中后立即同步执行操作。
    • 谢谢。我需要返回 File 而不是 Observable,因为我的类实现了某些我无法更改的接口。我猜 RxJava 不适合我的情况。
    • 有办法的。 RxJava 有一个名为 .toBlocking() 的方法,它将其转换为 BlockingObservable。 BO 有一个名为 .first() 的方法,它同步返回接收到的第一个元素。在这种情况下,以这种方式使用 RxJava 并没有获得任何好处。我将其添加到示例中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    相关资源
    最近更新 更多