Transform Callback into Observable with data from other Observable

42 views Asked by At

I'm new to RxJava and I got a question about transforming callbacks into Observables.

I have this function that uses a callback.

client.loadAsync(body, object : Callback {
   override fun onSuccess(response: AwesomeResponse) {
      // Successful response!
   }
   
   override fun onError(exception: Exception) {
      // Error response!
   }
})

For this, I use Single.create

Single.create {
   client.loadAsync(body, object : Callback {
      override fun onSuccess(response: AwesomeResponse) {
         it.onSuccess(response)
      }
   
      override fun onError(exception: Exception) {
         it.onError(exception)
      }
   })
}

The problem comes from the body parameter, to build it I need data from another observable.

This is what I'm doing right now.

otherObservable.doOnNext { dto -> 
   val body = clientBody(id = dto.Id)

   Single.create {
      client.loadAsync(body, object : Callback {
         override fun onSuccess(response: AwesomeResponse) {
            it.onSuccess(response)
         }

         override fun onError(exception: Exception) {
            it.onError(exception)
         }
      })
   }
   .subscribeOn(scheduler)
   .subscribe(
      { uiReportSubject.onNext(it) }, 
      {}, 
      compositeDisposable
   )
}
.subscribeOn(scheduler)
.subscribe()

I'm receiving the data into my UI through the subscription of the uiReportSubject object which is a BehaviourSubject

My question is, is this the right way to do this? or is there a better way to do this? Like an operator (like map) or something like that?

Thanks

0

There are 0 answers