安卓RxJava结合Retrofit发送单个或多个网络请求(串行
2020-05-12 本文已影响0人
蓝不蓝编程
目标
采用RxJava和Retrofit,发送单个或多个网络请求(串行),并更新UI.
实现方案
发送单个网络请求方案
- 修改app工程的build.gradle文件
- 在android节点下添加如下信息
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
- 添加依赖
implementation 'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.2'
- 定义数据类Task.kt
data class Task(val id: Int, var name: String)
- 创建网络接口类NetworkService.kt
interface NetworkService {
@GET("cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json")
fun query(): Observable<Task>
}
- 创建网络工具类NetworkUtils.kt
fun getNetworkService(): NetworkService {
val okHttpClient = OkHttpClient.Builder().build()
val retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://gitee.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
return retrofit.create(NetworkService::class.java)
}
- activity调用
private fun queryData() {
val networkService = getNetworkService()
networkService.query()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { t -> contentTv.text = t.name }
}
发送两个网络请求方案
- 修改app工程的build.gradle文件,同上
- 定义数据类Task.kt,同上
- 创建网络接口类NetworkService.kt
interface NetworkService {
@GET("cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json")
fun query(): Observable<Task>
@GET("cxyzy1/AndroidAsyncTaskDemo/raw/master/data2.json")
fun query2(): Observable<Task>
}
- 创建网络工具类NetworkUtils.kt,同上
- activity调用
private fun queryData() {
val networkService = getNetworkService()
networkService.query()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { contentTv.text = it.name }
.observeOn(Schedulers.io())
.flatMap { return@flatMap networkService.query2() }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ contentTv2.text = it.name },
{ Log.e("MainActivity2", it.message) }, {})
}
代码说明:
先调用query接口,然后再调用query2接口.
完整源代码
https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/tree/master/rxjavaDemo