Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle empty response with retrofit and rxjava 2.x

Tags:

When using rxjava 1.x i used to return Observable<Void> to handle empty response from retrofit:

@POST( "login" ) Observable<Void> getToken( @Header( "Authorization" ) String authorization,                                        @Header( "username" ) String username,                                        @Header( "password" ) String password ); 

But since rxjava 2.x won't emit anything with Void is there any good practice to handle those empty responses?

like image 310
Samuel Eminet Avatar asked Jan 09 '17 23:01

Samuel Eminet


People also ask

How do you handle an empty response in retrofit?

You can just return a ResponseBody , which will bypass parsing the response. Even better: Use Void which not only has better semantics but is (slightly) more efficient in the empty case and vastly more efficient in a non-empty case (when you just don't care about body).

What is the difference between RxJava and retrofit?

Rx gives you a very granular control over which threads will be used to perform work in various points within a stream. To point the contrast here already, basic call approach used in Retrofit is only scheduling work on its worker threads and forwarding the result back into the calling thread.

Is RxJava deprecated?

RxJava, once the hottest framework in Android development, is dying. It's dying quietly, without drawing much attention to itself. RxJava's former fans and advocates moved on to new shiny things, so there is no one left to say a proper eulogy over this, once very popular, framework.


2 Answers

Completable was designed for such cases. It available since RxJava 1.1.1. From the official docs:

Represents a deferred computation without any value but only indication for completion or exception. The class follows a similar event pattern as Reactive-Streams: onSubscribe (onError|onComplete)?

So just change your method's return type:

@POST("login") Completable getToken(@Header("Authorization") String authorization,                      @Header("username")      String username,                      @Header("password")      String password); 

And rewrite your subscriber, e.g.:

apiManager.getToken(auth, name, pass)     ...     .subscribe(() -> {         //success     }, exception -> {         //error     }); 
like image 120
Maksim Ostrovidov Avatar answered Dec 19 '22 08:12

Maksim Ostrovidov


Another solution is:

@POST("login") Observable<Response<Void>> getToken(@Header("Authorization") String authorization,                                     @Header("username") String username,                                     @Header("password") String password); 

Update: But I would rather use Completable

like image 23
Leonid Ustenko Avatar answered Dec 19 '22 09:12

Leonid Ustenko