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

相关文章

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3