1)配置

dependencies{
...
compile 'io.reactivex:rxjava:1.2.0'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:retorfit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
}

2)修改请求网络接口

Retrofit请求接口返回Call。若结合RxJava,则需要把Call改为Observable

public interface IpServiceForPost{
@FormUrlEncoded
@POST("getIpInfo.php")
Observable<IpModel> getIpMsg(@Field("ip") String first);
}

3)修改请求网络方法

private void postIpInformation(String ip){
String url = "http://ip.taobao.com/service/";
Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
IpServiceForPost ipService = retrofit.create(IpServcieForPost.class);
subscription=ipService.getIpMsg(ip).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<IpModel>(){
@Override
public void onCompleted(){
Log.d(TAG,"onCompleted");
}
@Override
public void onError(Throwable e){
Log.d(TAG,"onError");
}
@Override
public void onNext(IpModel ipModel){
String country=ipModel.getData().getCountry();
Toast.makeText(getApplicationContext(),country,Toast.LENGTH_SHORT).show();
}
});
}

4)请求返回数据格式封装

public class IpModel{
private int code;
private IpData data;
public void setCode(int code){
this.code = code;
}
public int getCode(){
return this.code;
}
...
}
public class HttpResult<T>{
private int code;
private T data;
public int getCode(){
return code;
}
public void setCode(int code){
this.code = code;
}
public T getData(){
return data;
}
public void setData(T data){
this.data = data;
}
}
public interface IpServiceForPost{
@FormUrlEncoded
@POST("getIpInfo.php")
Observable<HttpResult<IpData>> getIpMsg(@Field("ip") String first);
}
private void postIpInformation(String ip){
...
subscription=ipService.getIpMsg(ip).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<HttpResult<IpData>>(){
@Override
public void onCompleted(){
}
@Override
public void onError(Throwable e){
}
@Override
public void onNext(HttpResult<IpData> ipDataHttpResult){
IpData data=ipDataHttpResult.getData();
Toast.matkText(getApplicationContext(),data.getCountry(),Toast.LENGTH_SHORT).show();
}
});
}

5)取消请求

@Override
public void onStop(){
super.onStop();
if(subscription!=null && subscription.isUnsubscribed()){
subscription.unsubscribe();
}
}
private CompositeSubscription compositeSubscription = new CompositeSubscription();
...
//发送请求的地方,将返回的subscription添加到compositeSubscription中
compositeSubscription.add(subscription);
...
//取消所有请求
@Override
public void onStop(){
super.onStop();
compositeSubscription.unsubscribe();
}

《Android进阶之光》--RxJava结合Retrofit访问网络的更多相关文章

  1. 《Android进阶之光》--RxJava

    No1: RxJava使用 dependencies{ compile 'io.reactivex:rxjava:1.2.0' compile 'io.reactivex:rxandroid:1.2. ...

  2. [置顶] 曙光到来,我的新书《Android进阶之光》已出版

    独立博客版本请点击这里 由来 2016年我开始建立了自己的知识体系,所有的文章都是围绕着这个体系来写,随着这个体系的慢慢成长,开始有很多出版社联系我写书,因为比较看好电子工业出版社,就顺理成章的开始了 ...

  3. 《Android进阶之光》--注解与依赖注入框架

    No1: 标准注解: 1)@Override:覆写 2)@Deprecated:过时 3)@SuppressWarnings:取消警告 4)@SafeVarargs:申明使用了可变长度参数的方法 No ...

  4. 《Android进阶之光》--Material Design

    接上篇<Android进阶之光>--Android新特性 No1: 组件: 1)底部工作条-Bottom Sheets 2)卡片-Cards 3)提示框-Dialogs 4)菜单-Menu ...

  5. Android进阶之光-第1章-Android新特性-读书笔记

    第 1 章 Android 新特性 1.1 Android 5.0 新特性 1.1.1 Android 5.0 主要新特性 1. 全新的 Material Design 新风格 Material De ...

  6. Android O 可以上网 提示无法访问网络

    android O连接Wifi,可以上网,但是却提示无法访问网络,并且在wifi图标上有一个'x'. 从android N开始引入了监控机制,每次连接都会访问一下google的服务器,由于国内被墙,所 ...

  7. rxjava 调用retrofit执行网络请求的过程

    retrofit流程图 -1.RxJava调用Retrofit,从requestGtPushSaeUserInfo()中获得被观察者observable,然后new一个观察者向它订阅   0.从业务中 ...

  8. 《Android进阶之光》--网络编程与网络框架

    No1: Volley源码分析: Volley.newRequestQueue-> RequestQueue.start()-> CacheDispatcher.start()->C ...

  9. 《Android进阶之光》--RxJava实现RxBus

    事件总线RxBus,替代EventBus和otto 1)创建RxBus public class RxBus{ private static volatile RxBus rxBus; private ...

随机推荐

  1. setTimeout设置不起作用

    setTimeout立刻调用了 a()方法而不是xx秒以后,是因为调用方法时候没有加双引号. 正确做法:setTimeout(" a() ",5000): 调用 a() 方法时候要 ...

  2. 记一次Win Server 2012部署问题及解决方法

    1.前言 本章内容为在win server 2012服务器部署时遇到的问题及解决方法.大致工作为:两台服务器,一台web.一台数据库:web服务器部署.net web程序,数据库服务器安装oracle ...

  3. caffe中 softmax 函数的前向传播和反向传播

    1.前向传播: template <typename Dtype> void SoftmaxLayer<Dtype>::Forward_cpu(const vector< ...

  4. zabbix3.0.4报错Get value from agent failed: cannot connect to [[1.1.1.1]:10050]: [4] Interrupted syste

    一.问题描述 部署完Zabbix agent之后,Server无法获取到数据.报错.报错信息如下: Get value from agent failed: cannot connect to [[1 ...

  5. Go语言规格说明书 之 内建函数(Built-in functions)

    go version go1.11 windows/amd64 本文为阅读Go语言中文官网的规则说明书(https://golang.google.cn/ref/spec)而做的笔记,介绍Go语言的 ...

  6. sqlserver服务启动后停止,传递给数据库 'master' 中的日志扫描操作的日志扫描号无效

    电脑异常重启,导致SqlServer服务启动后,自动停止,在[计算机管理]-[事件查看器]-[windows日志]中进行查看系统错误日志,在[应用程序]下发现可能的错误信息有以下两条: 1.错误:传递 ...

  7. Redhat5_linux 系统环境下 oracl11g的安装教程图解

    linux_oracl11g 安装步骤 操作系统的安装敬请参考此文:VM 安装 linux Enterprise_R5_U4_Server_I386_DVD教程图解 设置linux服务器的静态地址请参 ...

  8. == 和 equal 区别

    在初学 Java 时,可能会经常碰到下面的代码: String str1 = new String("hello"); String str2 = new String(" ...

  9. Oracle中数值的计算

    运算符 含义 · +(加)   加法 · ||(加) 字符串相加 · -(减)   减法 · *(乘)   乘法 · /(除)   除法 · mod(模)返回一个除法的整数余数  例如,12 % 5 ...

  10. 【C++ Primer 第13章】5. 动态内存管理类

    StrVec类的设计 [题目描述]:我们将实现标准库vector类的一个简化版本,我们所做的一个简化是不使用模板,我们类只用于string,因此,它被命名为StrVec. #include<io ...