栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Retrofit-+-OkHttp3-+-coroutines-,震撼发布

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Retrofit-+-OkHttp3-+-coroutines-,震撼发布

coroutines

kotlin较Java的最大变化就是kotlin推出的coroutines (协程),协程完全可以替代RxJava, Thread、多级接口回调等,并且有上下文及各种模式来迎合各种场景,具体不再这里解释,

使用上述出现的几个框架完成新的网络请求框架的封装 二、组合框架 2.1 添加依赖

//LifeCycle
implementation ‘androidx.lifecycle:lifecycle-common:2.2.0’
implementation ‘androidx.lifecycle:lifecycle-runtime:2.2.0’
implementation ‘android.arch.lifecycle:extensions:2.2.0’
implementation ‘androidx.lifecycle:lifecycle-livedata-ktx:2.2.0’

//Retrofit
implementation “com.squareup.retrofit2:retrofit:2.9.0”
implementation “com.squareup.okhttp3:logging-interceptor:4.2.0”
implementation “com.squareup.retrofit2:converter-gson:2.9.0”
implementation ‘com.squareup.retrofit2:converter-scalars:2.6.2’
//Coroutines
implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7’

//Kotlin extensions for activity and fragments
implementation ‘androidx.fragment:fragment-ktx:1.2.5’
implementation “androidx.activity:activity-ktx:1.1.0”

// Kotlin + coroutines
implementation “androidx.work:work-runtime-ktx:2.3.4”

// optional - RxJava2 support
implementation “androidx.work:work-rxjava2:2.3.4”

// optional - GCMNetworkManager support
implementation “androidx.work:work-gcm:2.3.4”

// optional - Test helpers
androidTestImplementation “androidx.work:work-testing:2.3.4”
implementation ‘org.conscrypt:conscrypt-android:2.2.1’

复制代码

具体根据需求添加

2.2 请求辅助类

状态管理

enum class Status {
SUCCESS,
ERROR,
LOADING
}
复制代码

请求结果处理类

class Resource(val status: Status, val data: T?, val message: String?) {
companion object {
fun success(data: T?) = Resource(Status.SUCCESS, data, null)
fun error(msg: String?, data: T?) = Resource(Status.ERROR, data, msg)
fun loading(data: T?) = Resource(Status.LOADING, data, null)
}
}

复制代码

2.3 使用Retrofit 创建API 接口、接口帮助类

将接口管理和请求放在不同的类文件中,方便管理

API 接口

interface ApiService {
@GET("{page}")
suspend fun getGirls(@Path(“page”) page: Int): Girls
}
复制代码

数据类将传到Demo中 Retrofit + OkHttp3 + coroutines + LiveData打造一款网络请求框架

API 接口类调用辅助类

class ApiHelper(private val apiService: ApiService) {
suspend fun getGirls() = apiService.getGirls(1)
}
复制代码

2.4 创建Retrofit及OkHttp等网络框架请求帮助类

object ServiceCreator {
private val okHttpClient by lazy { OkHttpClient().newBuilder() }
private val retrofit: Retrofit by lazy {
val builder = Retrofit.Builder()
.baseUrl(“https://gank.io/api/v2/data/category/Girl/type/Girl/page/1/count/”)
.addConverterFactory(GsonConverterFac
tory.create())
val dispatcher = Dispatcher()
dispatcher.maxRequests = 1
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
okHttpClient
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(com.kpa.network.data.http.interceptor.HttpLoggingInterceptor())
.dispatcher(dispatcher)
builder.client(okHttpClient.build()).build()
}

fun create(clazz: Class): T = retrofit.create(clazz)

inline fun createService(clazz: Class): T =
create(clazz)

}
复制代码

使用懒加载,将需要的配置在此处配置好,inline 对函数再次调用,可以查一下这样用的优点。

2.5 创建数据仓库

数据仓库的创建是为了能在此处处理数据,可能存在需要存储或者重构的数据,也是将数据的处理和ViewModel分离开,专职做数据处理,ViewModel 做数据周转

class MainRepository(private val apiHelper: ApiHelper) {
suspend fun getGirls() = apiHelper.getGirls()
}
复制代码

2.6 ViewModel

一般在使用ViewModel 的时候都是于一个或者一组逻辑相关的页面对应,将数据更加独立、清晰

class MainViewModel(private val mainRepository: MainRepository) : ViewModel() {
fun getGirls() = liveData(Dispatchers.IO) {
emit(Resource.loading(null))
try {
emit(Resource.success(mainRepository.getGirls()))
} catch (e: Exception) {
emit(Resource.error(e.message, null))
}
}
{
emit(Resource.loading(null))
try {
emit(Resource.success(mainRepository.getGirls()))
} catch (e: Exception) {
emit(Resource.error(e.message, null))
}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/710002.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号