Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx

上传人:b****4 文档编号:4910183 上传时间:2022-12-11 格式:DOCX 页数:13 大小:388.05KB
下载 相关 举报
Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx_第1页
第1页 / 共13页
Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx_第2页
第2页 / 共13页
Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx_第3页
第3页 / 共13页
Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx_第4页
第4页 / 共13页
Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx_第5页
第5页 / 共13页
点击查看更多>>
下载资源
资源描述

Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx

《Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx》由会员分享,可在线阅读,更多相关《Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx(13页珍藏版)》请在冰豆网上搜索。

Retrofit20 RxJava Dragger2实现不一样的Android网络架构搭建DOC.docx

Retrofit20RxJavaDragger2实现不一样的Android网络架构搭建DOC

Retrofit2.0+RxJava+Dragger2实现不一样的Android网络架构搭建

封装实现网络框架这种行为固然不错,但是这需要自身具备比较高的能力,而很多时候我们没有那样的能力把它封装的足够好。

这时我们使用开源的网络框架也未尝不是一件好事,github上面知名的网络框架已经经过了很多app的验证,在一定意义上是非常符合我们在实际的项目开发所需要的。

Android开发中几个知名的开源的网络框架有android-async-http,Volley,OkHttp等,国人开发的xUtils快速开发框架也比较流行。

android-async-http是个很老牌的网络框架,非常的经典。

Volley官方推荐的,自不必说。

OkHttp可以说是后起之秀,现在非常流行,Android系统底层api都有用到,所以是非常niubility.

我们很多开发者大都在小型公司,不了解大公司是怎么做Android网络框架的,也想知道那些用户量过千万的APP到底用了些什么技术,下面有两张图片,让我们一起来了解一下Android版的美团和Uber到底用了些什么技术。

  

Uber

看完你会发现其实这些用户量过亿的APP也使用了很多的开源框架,而且这些开源框架中大多数其实都是我们平常在开发中所常用到的,并不陌生。

可能大多数人对Retrofit,Rxjava这些还不太熟悉,那话不多说,今天我们就来讲讲怎么用Retrofit2.0+RxJava+Dragger2来实现Android网络构架搭建,给大家提供一种思路,供大家参考参考。

 RxJava是一种响应式编程框架,采用观察者设计模式。

最核心的是Observables(被观察者,事件源)和Subscribers(观察者)这两个东西,RxAndroid是Rxjava在Android上的实现。

  Dragger2   

  -是一种依赖注入框架,可以大大节省我们的代码量,便于维护。

在这里我就不费过多笔墨来介绍着三个东西了,今天的主题是提供一种如何搭建一个不一样的网络框架的思路。

如果读者对这三个框架不是很了解的话,可以自行的Google脑补一下。

  

  首先,就是开始把这些框架引入到咱们的项目中来作为依赖库,在app/build.gradle文件中添加

  

applyplugin:

'com.android.application'

applyplugin:

'com.neenbedankt.android-apt'

android{

compileSdkVersion23

buildToolsVersion"23.0.2"

defaultConfig{

applicationId"com.finddreams.retrofit"

minSdkVersion15

targetSdkVersion23

versionCode1

versionName"1.0"

}

buildTypes{

release{

minifyEnabledfalse

proguardFilesgetDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'

}

}

}

dependencies{

compilefileTree(include:

['*.jar'],dir:

'libs')

testCompile'junit:

junit:

4.12'

compile'com.android.support:

appcompat-v7:

23.1.1'

//retrofit

compile'com.squareup.retrofit2:

retrofit:

2.0.0-beta4'

//gson解析

compile'com.squareup.retrofit2:

converter-gson:

2.0.0-beta4'

//rxjava

compile'io.reactivex:

rxandroid:

1.1.0'

compile'com.squareup.retrofit2:

adapter-rxjava:

2.0.0-beta4'

//dragger2

provided'org.glassfish:

javax.annotation:

10.0-b28'

apt'com.google.dagger:

dagger-compiler:

2.0.2'

compile'com.google.dagger:

dagger:

2.0.2'

}

因为Dragger2是基于注解的,它会预先生成一些类文件,所以需要在整个项目的/build.gradle文件中加上apt工具:

buildscript{

repositories{

jcenter()

}

dependencies{

classpath'com.android.tools.build:

gradle:

2.0.0-beta6'

classpath'com.neenbedankt.gradle.plugins:

android-apt:

1.8'

//NOTE:

Donotplaceyourapplicationdependencieshere;theybelong

//intheindividualmodulebuild.gradlefiles

}

}

allprojects{

repositories{

jcenter()

}

}

taskclean(type:

Delete){

deleterootProject.buildDir

}

接着开始写一个提供Retrofit的单例类:

  

/**

*Retrofit的实体类

*/

publicclassRestApiAdapter{

privatestaticRetrofitretrofit=null;

publicstaticRetrofitgetInstance(){

if(retrofit==null){

GsonConverterFactorygsonConverterFactory=GsonConverterFactory.create();

OkHttpClientokHttpClient=newOkHttpClient();

OkHttpClient.Builderbuilder=okHttpClient.newBuilder();

builder.retryOnConnectionFailure(true);

retrofit=newRetrofit.Builder().client(okHttpClient)

.baseUrl(ConstantApi.BaiduUrl)

.addConverterFactory(gsonConverterFactory)

.addCallAdapterFactory(RxJavaCallAdapterFactory.create())

.build();

}

returnretrofit;

}

}

addCallAdapterFactory(RxJavaCallAdapterFactory.create())这个方法就是RxJava和Retrofit结合的关键。

接着我们为Retrofit提供一个service接口,声明api接口地址和所需要的参数,这里我们使用XXAPI提供的天气接口,实现根据城市名称查询天气的功能,接口地址:

代码如下:

`/**

*天气接口Api

*/

publicinterfaceWeatherApiService{

/**

*查询天气

*/

@GET("apistore/weatherservice/cityname")

ObservablequeryWeather(@Header("apikey")Stringapikey,@Query("cityname")Stringcityname);

}`

返回一个Observable被观察者/事件源的意思是交给RxJava来处理。

然后我们写一个BaseSubsribe观察者来管理网络请求开始结束,成功与失败:

publicabstractclassBaseSubsribeextendsSubscriber{

privatestaticfinalStringTAG="BaseSubsribe";

@Override

publicvoidonStart(){

super.onStart();

Log.i(TAG,"onStart");

}

@Override

publicvoidonNext(Tt){

Log.i(TAG,"response"+t.toString());

onSuccess(t);

}

@Override

publicvoidonCompleted(){

Log.i(TAG,"onCompleted");

}

publicabstractvoidonSuccess(Tresult);

@Override

publicvoidonError(Throwablee){

e.printStackTrace();

Log.i(TAG,"onError"+e.getMessage());

}

}

接着我们写一个WeatherInteractor接口连接service类:

   

publicinterfaceWeatherInteractor{

SubscriptionqueryWeather(Stringapikey,Stringcityname,BaseSubsribesubsribe);

}

   然后是这个接口的实现类:

publicclassWeatherInteractorImplimplementsWeatherInteractor{

privatefinalWeatherApiServiceapi;

@Inject

publicWeatherInteractorImpl(WeatherApiServicemyApi){

this.api=myApi;

}

@Override

publicSubscriptionqueryWeather(Stringapikey,Stringcityname,BaseSubsribesubsribe){

Observableobservable=api.queryWeather(apikey,cityname);

Subscriptionsubscribe=observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(subsribe);

returnsubscribe;

}

}

接下来是如何使用Dragger2的时候,知道Dragger2的都知道有几个概念,一个是Module:

主要提供依赖对象比如context,restapi…;一个是@inject:

注解,用在需要依赖对象的地方;另一个是Componet:

用来连接Module和@inject

   

首先定义一个Module类,提供需要注入依赖的对象:

Module类

@Module

publicclassInteractorModule{

@Pvides

publicRetrofitprovideRestAdapter(){

returnRestApiAdapter.getInstance();

}

@Provides

publicWeatherApiServiceprovideHomeApi(RetrofitrestAdapter){

returnrestAdapter.create(WeatherApiService.class);

}

@Provides

publicWeatherInteractorprovideHomeInteractor(WeatherApiServicemyApi){

returnnewWeatherInteractorImpl(myApi);

}

}

接着是写一个Componet类:

/**

*声明AppComponent组件

*

*@authorfinddreams

*@address

*/

@Singleton

@Component(

modules={

InteractorModule.class,

}

publicinterfaceAppComponent{

voidinject(Appapp);

WeatherInteractorgetWeatherInteractor();

}

   然后我们在Application中初始化这个AppComponent:

/**

*Application类

*

*@authorfinddreams

*@address

*/

publicclassAppextendsApplication{

privateAppComponentcomponent;

@Override

publicvoidonCreate(){

super.onCreate();

setDraggerConfig();

}

publicAppComponentcomponent(){

returncomponent;

}

publicstaticAppget(Contextcontext){

return(App)context.getApplicationContext();

}

/**

*初始化Dragger,DaggerAppComponent是自动生成,需要Rebuild

*/

privatevoidsetDraggerConfig(){

component=DaggerAppComponent.builder().interactorModule(newInteractorModule())

ld();

component.inject(this);

}

}

这里需要注意的是,由于Dagger2是预编译生成一个类,所以我们需要Rebuild项目,才会生成DaggerAppComponent这个类。

如果开发中出现

importcom.finddreams.retrofit.api.config.DaggerAppComponent;

找不到这个类的错误

 这时就需要重新的Rebuild项目

   

最后我们就可以在Activity中开始使用了:

/**

*主页

*

*@authorfinddreams

*@address

*/

publicclassMainActivityextendsAppCompatActivity{

privateAppComponentcomponent;

privateWeatherInteractorweatherInteractor;

privateEditTextcity;

privateTextViewqueryresult;

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

city=(EditText)findViewById(R.id.city);

queryresult=(TextView)findViewById(R.id.queryresult);

//获取到AppComponent组件

component=App.get(this).component();

//通过AppComponent拿到WeatherInteractor

weatherInteractor=component.getWeatherInteractor();

findViewById(R.id.query).setOnClickListener(newView.OnClickListener(){

@Oide

publicvoidonClick(Viewv){

queryWeatherData();

}

});

}

publicvoidqueryWeatherData(){

Stringcontent=city.getText().toString();

//调用查询天气接口的方法

Subscriptionsubscription=weatherInteractor.queryWeather(ConstantApi.baiduKey,content,newBaseSubsribe(){

@Override

publicvoidonSuccess(WeatherResultBeanresult){

WeatherResultBean.RetDataEntityretData=result.getRetData();

queryresult.setText(retData.getCity()+":

"+retData.getWeather()+":

"+retData.getDate());

}

@Override

publicvoidonError(Throwablee){

super.onError(e);

queryresult.setText("查询失败");

}

}

);

//取消请求

//subscription.unsubscribe();

}

}

我们看下项目运行的结果图:

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 求职职场 > 简历

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1