android - How to return value with RxJava? -
let's consider situation. have class has 1 method returns value:
public class foo() { observer<file> fileobserver; observable<file> fileobservable; subscription subscription; public file getmethatthing(string id) { // implement logic in observable<file> , return value // emitted in onnext(file) } }
how return value received in onnext
? correct approach? thank you.
you need better understanding of rxjava first, observable -> push model is. solution 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 app public void doingthings(){ ... // synchronous foo.getmethatthing(5) .subscribe(new onsubscribed<file>(){ public void onnext(file file){ // file } public void oncomplete(){ } public void onerror(throwable t){ // error cases } }); // asynchronous, each observable subscription whole operation scratch foo.getmethatthing("5") .subscribeon(schedulers.newthread()) .subscribe(new onsubscribed<file>(){ public void onnext(file file){ // file } public void oncomplete(){ } public void onerror(throwable t){ // error cases } }); // synchronous , blocking, run operation on thread while current 1 stopped waiting. // warning, danger, never in main/ui thread or may freeze app file file = foo.getmethatthing("5") .subscribeon(schedulers.newthread()) .toblocking().first(); .... }
Comments
Post a Comment