Retrofit使用教程(三):Retrofit与RxJava初相逢(个人感觉好理解一些)

2024-06-03 12:48

本文主要是介绍Retrofit使用教程(三):Retrofit与RxJava初相逢(个人感觉好理解一些),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

上一篇文章讲述了Retrofit的基本使用,包括GET,POST等请求.今天的文章中Retrofit要与RxJava配合使用.

了解RxJava

RxJava有种种好处,我不在这里一一讲述.这里我只给出一个使用RxJava的例子.如果想更深入地了解RxJava,可以参考以下文章:

给Android开发者的RxJava详解

RxJava Essentials 中文翻译版

接下来的文章,我也会写RxJava的进一步使用的.

案例说明

该例子是获取手机上安装的APP,然后列表显示包括名称,图标,安装时间等信息.

上代码

下面是自定义的 AppInfo 类,包含名称,图标,安装时间,版本号,版本名称等属性.

public class AppInfo {private String name;private String installTime;private int versionCode;private String versionName;private Drawable icon;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getInstallTime() {return installTime;}public void setInstallTime(String installTime) {this.installTime = installTime;}public int getVersionCode() {return versionCode;}public void setVersionCode(int versionCode) {this.versionCode = versionCode;}public String getVersionName() {return versionName;}public void setVersionName(String versionName) {this.versionName = versionName;}public Drawable getIcon() {return icon;}public void setIcon(Drawable icon) {this.icon = icon;}@Overridepublic String toString() {return "AppInfo{" +"name='" + name + '\'' +", installTime='" + installTime + '\'' +", versionCode='" + versionCode + '\'' +", versionName='" + versionName + '\'' +", icon=" + icon +'}';}
}

下面是获取AppLie表的代码,封装为工具类使用:

public class AppUtil {/*** 获取已安装的APP的列表* @param context 上下文* @return AppInfo列表*/public static List<AppInfo> getAppList(Context context){List<AppInfo> appInfoList = new ArrayList<>();List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);for (PackageInfo packageInfo : packages) {AppInfo appInfo = new AppInfo();appInfo.setName(packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString());appInfo.setIcon(packageInfo.applicationInfo.loadIcon(context.getPackageManager()));appInfo.setInstallTime(getFormatTime(packageInfo.firstInstallTime));appInfo.setVersionCode(packageInfo.versionCode);appInfo.setVersionName(packageInfo.versionName);appInfoList.add(appInfo);}return appInfoList;}public static String getFormatTime(long time){if (time <= 0){return "";}return SimpleDateFormat.getDateInstance(DateFormat.FULL).format(new Date(time));}
}

不使用RxJava怎么做?

我们在不适用RxJava时怎么做?通常新建一个子线程去执行任务,然后回调更新界面,对不对?

private void getByNormal() {refreshLayout.setRefreshing(true);infoList.clear();appAdapter.notifyDataSetChanged();new AsyncTask<Void, Void, List<AppInfo>>(){@Overrideprotected List<AppInfo> doInBackground(Void... params) {return AppHelper.getHelper().getListByNormal(MainActivity.this);}@Overrideprotected void onPostExecute(List<AppInfo> appInfos) {infoList.addAll(appInfos);appAdapter.notifyDataSetChanged();refreshLayout.setRefreshing(false);}};
}

使用RxJava

使用RxJava是这样来写代码的:

1.创建 Observable

public Observable<List<AppInfo>> getListByRxJava(final Context context){Observable<List<AppInfo>> observer = Observable.create(new Observable.OnSubscribe<List<AppInfo>>() {@Overridepublic void call(Subscriber<? super List<AppInfo>> subscriber) {List<AppInfo> infoList = AppUtil.getAppList(context);subscriber.onNext(infoList);subscriber.onCompleted();}});return observer;
}

2.在界面出调用

private void getByRxJava() {refreshLayout.setRefreshing(true);infoList.clear();appAdapter.notifyDataSetChanged();AppHelper.getHelper().getListByRxJava(this).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<List<AppInfo>>() {@Overridepublic void onCompleted() {appAdapter.notifyDataSetChanged();refreshLayout.setRefreshing(false);}@Overridepublic void onError(Throwable e) {}@Overridepublic void onNext(List<AppInfo> list) {infoList.addAll(list);}});
}

看结果

这个Demo的源码在此: RxJavaDemo

在Retrofit中使用RxJava

上次我们获取手机的归属地时的 PhoneService 中是这样写的:

@GET("/apistore/mobilenumber/mobilenumber")
Call<PhoneResult> getResult(@Header("apikey") String apikey,@Query("phone") String phone);

返回了一个Call对象,使用RxJava我们则返回一个可被观测的 PhoneResult : Observable<PhoneResult> ,如下:

@GET("/apistore/mobilenumber/mobilenumber")
Observable<PhoneResult> getPhoneResult(@Header("apikey") String apikey,@Query("phone") String phone);

为了能返回此对象,我们需要在创建Retrofit对象时添加一个RxJava对象的Adapter来自动完成:

Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();

为此,还封装了一个单例模式的 PhoneApi 类:

/*** 手机号相关的API* Created by Asia on 2016/3/24 0024.*/
public class PhoneApi {/*** HOST地址*/public static final String BASE_URL = "http://apis.baidu.com";/*** 开发者Key*/public static final String API_KEY = "8e13586b86e4b7f3758ba3bd6c9c9135";/*** 获取PhoneApi实例* @return*/public static PhoneApi getApi(){return ApiHolder.phoneApi;}static class ApiHolder{private static PhoneApi phoneApi = new PhoneApi();}private PhoneService service;private PhoneApi(){Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();service = retrofit.create(PhoneService.class);}/*** 获取PhoneService实例* @return*/public PhoneService getService(){return service;}
}

下面就是使用去获取手机的归属地啦:

phoneService.getPhoneResult(PhoneApi.API_KEY, number).subscribeOn(Schedulers.newThread())    //子线程访问网络.observeOn(AndroidSchedulers.mainThread())  //回调到主线程.subscribe(new Observer<PhoneResult>() {@Overridepublic void onCompleted() {}@Overridepublic void onError(Throwable e) {}@Overridepublic void onNext(PhoneResult result) {if (result != null && result.getErrNum() == 0) {PhoneResult.RetDataEntity entity = result.getRetData();resultView.append("地址:" + entity.getCity());}}});
}

运行一下吧,结果是同样的哈.

项目地址在此: Dev-Wiki/RetrofitDemo

更多文章请移步我的博客:DevWiki Blog

重要说明

想随时获取最新博客文章更新,请关注公共账号DevWiki,或扫描下面的二维码:

这篇关于Retrofit使用教程(三):Retrofit与RxJava初相逢(个人感觉好理解一些)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4