本文介绍了使用改造和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:

因此只需更改方法的返回类型:

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处理空响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 10:54
查看更多