本文介绍了如何使用RxJava返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's consider this situation. We have some class which has one method which returns some value:

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

How to return that value which was received in onNext? What would be the correct approach? Thank you.

推荐答案

首先,您需要更好地了解RxJava,即Observable-> push模型是什么.这是供参考的解决方案:

You need a better understanding of RxJava first, what the Observable -> push model is. This is the solution for reference:

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返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:28