RXjava+Retrofit封装:对观察者Observer进行封装,实现代码复用和拓展

本文主要是介绍RXjava+Retrofit封装:对观察者Observer进行封装,实现代码复用和拓展,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在使用rxjava+retrofit处理网络请求的时候,一般会采用对观察者进行封装,实现代码复用和拓展

public class FObserver<T> implements Observer<T> {private Disposable mDisposable;private ResultCallback mCallback;public FObserver(ResultCallback callback) {this.mCallback = callback;}@Overridepublic void onSubscribe(Disposable d) {this.mDisposable = d;}@Overridepublic void onNext(T t) {try {doOnNext(t);} catch (Exception e) {
//            FLog.e(e);onError(e);}disposeObserver();}public void doOnNext(T t) throws Exception {if (mCallback != null) {mCallback.onResult(t);}}@Overridepublic void onError(Throwable e) {
//        FLog.d("onError + " + e);FResult result = new FResult(FError.GENERAL_ERROR);result.setExceptionClassName(e.getClass().getSimpleName());if (e instanceof HttpException) {result = parseHttpException((HttpException) e);} else if (e instanceof NetworkErrorException|| e instanceof SocketTimeoutException|| e instanceof ConnectException|| e instanceof SocketException|| e instanceof UnknownHostException|| e instanceof NoRouteToHostException|| e instanceof TimeoutException) {result.setErrorCode(FError.NETWORK_ERROR.getValue());}else if(e instanceof JsonSyntaxException){result.setErrorCode(FError.JSON_PARSER_ERROR.getValue());}try {onError(result);} catch (Throwable throwable) {FLog.e(throwable);} finally {disposeObserver();}}private FResult parseHttpException(HttpException httpException) {FResult result = new FResult(FError.HTTP_ERROR);try {result.setHttpCode(httpException.code());result.setExceptionClassName(httpException.getClass().getSimpleName());String errorBodyStr = httpException.response().errorBody().string();JsonObject errorBody = new Gson().fromJson(errorBodyStr, JsonObject.class);result.setTimestamp(getJsonValue(errorBody, "timestamp"));result.setStatus(getJsonValue(errorBody, "status"));result.setMessage(getJsonValue(errorBody, "error"));result.setException(getJsonValue(errorBody, "exception"));result.setException(getJsonValue(errorBody, "message"));result.setPath(getJsonValue(errorBody, "path"));} catch (IOException | JsonIOException e) {FLog.e(e);}return result;}public static String getJsonValue(JsonObject object, String elementName) {if (object == null || TextUtils.isEmpty(elementName)) {return "";}if (!object.has(elementName)) {return "";}if (object.get(elementName).isJsonNull()) {return "";}return object.get(elementName).getAsString();}public void onError(FResult result) {if (mCallback != null) {mCallback.onError(result);}}@Overridepublic void onComplete() {disposeObserver();}private void disposeObserver() {try {if (mDisposable != null) {mDisposable.dispose();}} catch (Exception ex) {FLog.e("disposeObserver", ex);}}
}
public interface ResultCallback<T> {void onError(FResult result);void onResult(T result);
}
public class FResult {private int errorCode;private String exceptionClassName;//only HttpExceptionprivate int httpCode;//FErrorDTO contentprivate String timestamp;private String status;private String error;private String exception;private String message;private String path;public FResult(FError ferror) {this.errorCode = ferror.getValue();this.message = ferror.name();}public FResult(int errorCode, String message) {this.errorCode = errorCode;this.message = message;}public FResult(int errorCode, String message, String path, String status, String timestamp) {this.errorCode = errorCode;this.message = message;this.path = path;this.status = status;this.timestamp = timestamp;}public void setErrorCode(int errorCode) {this.errorCode = errorCode;}public void setExceptionClassName(String exceptionClassName) {this.exceptionClassName = exceptionClassName;}public void setHttpCode(int httpCode) {this.httpCode = httpCode;}public void setTimestamp(String timestamp) {this.timestamp = timestamp;}public void setStatus(String status) {this.status = status;}public void setError(String error) {this.error = error;}public void setException(String exception) {this.exception = exception;}public void setMessage(String message) {this.message = message;}public void setPath(String path) {this.path = path;}private String geTime(String timestamp) {if (timestamp == null) {return "";}try {Date date = new Date(Long.decode(timestamp));return date.toLocaleString();} catch (Exception e) {FLog.e(e);}return "";}public int getErrorCode() {return errorCode;}public String getExceptionClassName() {return exceptionClassName;}public int getHttpCode() {return httpCode;}public String getTimestamp() {return timestamp;}public String getStatus() {return status;}public String getError() {return error;}public String getException() {return exception;}public String getMessage() {return message;}public String getPath() {return path;}@Overridepublic String toString() {return "FResult{" +"errorCode=" + errorCode +", exceptionClassName='" + exceptionClassName + '\'' +", httpCode=" + httpCode +", timestamp='" + timestamp + '\'' +", status='" + status + '\'' +", error='" + error + '\'' +", exception='" + exception + '\'' +", message='" + message + '\'' +", path='" + path + '\'' +'}';}
}

应用

api.getRadioListFree(putBaseMap(request.toMap())).subscribe(new FObserver<RadioListFreeRes>(callback));
//api
@GET(Constants.BASE_PATH + Constants.SERVICE_getLyric)Observable<RadioListFreeRes> getRadioListFree(@QueryMap Map<String, String> map);

关于disposable
rxjava虽然好用,但是总所周知,容易遭层内存泄漏。也就说在订阅了事件后没有及时取阅,导致在activity或者fragment销毁后仍然占用着内存,无法释放。而disposable便是这个订阅事件,可以用来取消订阅
在oError和onComplete后调用disposable.dispose();

参考链接:https://www.cnblogs.com/zhujiabin/p/9294263.html

这篇关于RXjava+Retrofit封装:对观察者Observer进行封装,实现代码复用和拓展的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/979230

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

C++中unordered_set哈希集合的实现

《C++中unordered_set哈希集合的实现》std::unordered_set是C++标准库中的无序关联容器,基于哈希表实现,具有元素唯一性和无序性特点,本文就来详细的介绍一下unorder... 目录一、概述二、头文件与命名空间三、常用方法与示例1. 构造与析构2. 迭代器与遍历3. 容量相关4

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

C++中悬垂引用(Dangling Reference) 的实现

《C++中悬垂引用(DanglingReference)的实现》C++中的悬垂引用指引用绑定的对象被销毁后引用仍存在的情况,会导致访问无效内存,下面就来详细的介绍一下产生的原因以及如何避免,感兴趣... 目录悬垂引用的产生原因1. 引用绑定到局部变量,变量超出作用域后销毁2. 引用绑定到动态分配的对象,对象

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三