Rxjava+Retrofit实现串行和并行网络请求功能

本文介绍了如何使用RxJava和Retrofit进行串行和并行网络请求。首先展示了添加依赖库和配置,接着利用开放接口演示了创建Api接口和服务类。通过封装并行(merge)和串行(flatmap)操作,实现了网络请求功能。在Android 6.0及以上版本,由于安全策略,需在AndroidManifest.xml中设置`android:usesCleartextTraffic="true"`来允许明文传输。
摘要由CSDN通过智能技术生成

 

现在越来越多的小伙伴使用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
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值