如何使用RxJava返回值?

use*_*562 10 android rx-java

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

如何归还收到的价值onNext?什么是正确的方法?谢谢.

MLP*_*CiM 30

首先需要更好地理解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();
  ....
}
Run Code Online (Sandbox Code Playgroud)

  • 有一种方法.RxJava有一个名为.toBlocking()的方法,它将它转换为BlockingObservable.BO有一个名为.first()的方法,它同步返回收到的第一个元素.在这种情况下,你没有通过这种方式使用RxJava获得任何东西.我将它添加到示例中. (11认同)