Rxjava And Retrofit To Handle Empty Data Response
Solution 1:
Several suggested options:
- As Gson parser will put null in fields with no data, so you can return the entire
BaseResponse
object and check the nullity of data property object at the Subscriber/Observer. You can simply wrap your T value with some
Optional
alike interface, which can have a value, or can have nothing (Java8Optional
probably not available with android, but you can come up with simple structure likeOptional
yourself), then on youronNext()
you can check whether you have a value or not.RxJava2 has new
Observable
type called Maybe, which either emit a single item -onSuccess
notification, or nothing -onComplete()
notification, (and also errors):onSubscribe (onSuccess | onCompleted | onError)?
You can use
flatMapMaybe
with bothObservable
orSingle
(from the Retrofit service interface), to map some response value to aMaybe
, in theflatMapMaybe
you can useMaybe.fromCallable
to return null like you did here,Maybe.fromCallable
will treat returned null as no items emitted, and you'll getonComplete()
, so you can distinguish between result case (onNext
) to the no items case (onComplete
).
Post a Comment for "Rxjava And Retrofit To Handle Empty Data Response"