现在越来越多的小伙伴使用RXJava了,Rxjava到底是什么呢?官方的api文档上的“异步”两个字揭漏了rxjava的本质,不错,他就是一个异步任务执行的方式,对于异步任务的具体理解可以参考之前的AsyncTask(当然仅仅是在概念上是一致的)。这个rxjava的作用主要就是通过构建Observable的对象实现对数据的操作,线程的灵活切换等。好了,废话不多说直接上代码。
第一步:我的app下的build.gradle文件依赖库,配置如下,这里因为Rxjava2.X系列和Retrofit2之间有冲突,所以就用的国外某大神的依赖。
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.xiaolinge.exer.gfmvpdemo"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.1.3'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.okhttp3:okhttp:3.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'
implementation 'com.google.dagger:dagger:2.4'
}
第二步:这里为了防止数据获取失败问题,我使用了网上的开放接口
http://api.apiopen.top/getSongPoetry?page=1&count=20 (获取宋代诗词的接口)
http://api.apiopen.top/getTangPoetry?page=1&count=20(获取唐代诗词的接口)
第三步:创建Api接口,添加BaseUrl常量。
public interface Api {
public static final String BASE_URL_POETRY = "http://api.apiopen.top/";
}
第四步:创建Service的服务类
public interface ApiService {
@GET("getSongPoetry")
Observable<SongPoetryBean&g