简体   繁体   中英

How Convert to Rx java Observable

I am trying to convert Void and Response type to Observable corresponding. I tried .just but .create not sure if I can use just or create to do this conversion. Thanks.

void getSomeValue(){
    Observable<Response> returnedObservable=getResponse();//How to convert this from Response to Observable<Response>
    Observable<Void> returnedObservable=doSomething();//How to convert this from Void to Observable<Void>
}

Void doSomething(){
   //some code...
   return null;
}

Response getResponse(){
  //some code....
  return someResponse;
}

Small note: RxJava provides several types of observables (see here ). For this case, there is no reason for returning an Observable<Void> , you can use a Completable : in fact, it represents a deferred computation without any value.

You can use the method fromCallable : this defers the execution of getResponse function until the Observable is subscribed. The eager approach consists to use just : it evaluates the function immediately in the current thread.

Observable<Response> response = Observable.fromCallable(this::getResponse);
Observable<Response> response = Observable.just(getResponse());

Same for Completable :

Completable something = Completable.fromAction(this::doSomething);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM