How to return value with RxJava?

后端 未结 1 2205
误落风尘
误落风尘 2021-02-20 02:13

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

public class Foo() {
    Observer fileObserver;
            


        
相关标签:
1条回答
  • 2021-02-20 03:05

    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();
      ....
    }
    
    0 讨论(0)
提交回复
热议问题