How to return a value using RxJava?

Consider this situation. We have some class that has one method that 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) } } 

How to return this value received in onNext ? What would be the right approach? Thanks.

+8
android rx-java
source share
1 answer

First you need to better understand RxJava, what is the Observable โ†’ push model. This solution is 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(); .... } 
+24
source share

All Articles