使用改造和rxjava 2.x处理空响应 [英] Handle empty response with retrofit and rxjava 2.x

查看:211
本文介绍了使用改造和rxjava 2.x处理空响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用rxjava 1.x时,我通常返回 Observable< Void> 来处理改装后的空响应:

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 );

但是由于rxjava 2.x不会使用 Void 发出任何消息,因此有什么好的做法来处理那些空响应?

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

推荐答案

可完成专为此类情况而设计.它自 RxJava 1.1.1起.来自官方文档:

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

表示没有任何值,仅指示完成或异常的延迟计算.该类遵循与Reactive-Streams类似的事件模式:onSubscribe(onError | onComplete)?

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
    });

这篇关于使用改造和rxjava 2.x处理空响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆