问题
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?
回答1:
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
});
回答2:
Another solution is:
@POST("login")
Observable<Response<Void>> getToken( @Header( "Authorization" ) String authorization,
@Header( "username" ) String username,
@Header( "password" ) String password );
回答3:
Did you try using Observable<Object>
?
This is from the official documentation of RxJava 2:
enum Irrelevant { INSTANCE; }
Observable<Object> source = Observable.create((ObservableEmitter<Object> emitter) -> {
System.out.println("Side-effect 1");
emitter.onNext(Irrelevant.INSTANCE);
System.out.println("Side-effect 2");
emitter.onNext(Irrelevant.INSTANCE);
System.out.println("Side-effect 3");
emitter.onNext(Irrelevant.INSTANCE);
});
source.subscribe(e -> { /* Ignored. */ }, Throwable::printStackTrace);
来源:https://stackoverflow.com/questions/41558805/handle-empty-response-with-retrofit-and-rxjava-2-x