Skip to content Skip to sidebar Skip to footer

Rxjava And Retrofit To Handle Empty Data Response

I use Rxjava and Retrofit to handle the response from an HTTP server. Most of the time, data response is in this format: { code: 'OK', data: {.....} } And sometimes, the data

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 (Java8 Optional probably not available with android, but you can come up with simple structure like Optional yourself), then on your onNext() 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 both Observable or Single (from the Retrofit service interface), to map some response value to a Maybe, in the flatMapMaybe you can use Maybe.fromCallable to return null like you did here, Maybe.fromCallable will treat returned null as no items emitted, and you'll get onComplete(), 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"