liveDataCallAdapter库 用来实现Retrofit+LiveData具有生命周期的网络请求
关于
因为最近在用java写一个模仿网易云音乐的博客教程,所以用到了retrofit+rxjava+okhttp3网络框架,因为项目是mvvm框架,所以难免会用到LiveData,它的优势如下:
所以也推荐用LiveData,使用rxjava也可以,就是要考虑一些内存泄漏等问题。
添加引用
liveDataCallAdapter
工程build:
allprojects {
repositories {
...
maven {
url 'https://jitpack.io' }
}
}
项目build:
implementation 'com.github.Tobeyr1:liveDataCallAdapter:1.0.2'
使用 (支持Java/Kotlin)
将其添加到你的retrofit的build中:
Retrofit.Builder()
.client(client)
.baseUrl(Constant.BaseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addCallAdapterFactory(LiveDataCallAdapterFactory.create()) //add this line to you httpService
.addConverterFactory(GsonConverterFactory.create())
.build();
修改调用api的地方:
@GET("lyric") //获取歌词
LiveData<ApiResponse<xxxx>> getLyric(@Query("id") long songId);
//默认使用方法是LiveData<ApiResponse<xxx>>,其中xxx为你自己的实体类