Get a LiveData responses from Retrofit.
@GET("posts/{id}")
fun getPost(@Path("id") postId: Int): LiveData<Resource<Post>>
A Retrofit2 Call Adapter for Android Architecture Components' LiveData. Works with Blueprint.
This library is distributed through Jitpack. To install it:
Add this line in the repositories
section of your project's build.gradle
file:
allprojects {
repositories {
maven { url "https://jitpack.io" } // this line
}
}
And this line in the dependencies
of your module's build.gradle
file:
dependencies {
implementation "com.github.gianlucalimbi:retrofit2-livedata-adapter:1.0.0" // this line
}
When creating a Retrofit instance, just add the adapter using the addCallAdapterFactory()
function.
Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(LiveDataCallAdapterFactory()) // this line
.client(okHttpClient)
.build()
You are now good to go, you can use LiveData<Resource<AnyClass>>
in your retrofit service interface, like this:
interface ApiService {
@GET("posts")
fun getPosts(): LiveData<Resource<List<Post>>>
@GET("posts/{id}")
fun getPost(@Path("id") postId: Int): LiveData<Resource<Post>>
}
This call adapter uses Blueprint's Resource class. You can check the Blueprint GitHub page for more documentation.
Blueprint also comes with a handy ResourceObserver class that you can use with this adapter.
val liveData = api.getPost(postId)
liveData.observe(lifecycleOwner, resourceObserver {
onSuccess { data ->
// data: Post -> the data returned from retrofit
}
onError { error ->
// error: Exception -> an instance of HttpException if the API call failed (status >= 400), another Exception otherwise
}
onLoading { data ->
// data: Post? -> always null
}
onChanged { resource ->
// resource: Resource<Post>? -> the raw resource contained in the LiveData
}
})