项目作者: leonardoxh

项目描述 :
A simple LiveData call adapter for retrofit
高级语言: Java
项目地址: git://github.com/leonardoxh/livedata-call-adapter.git
创建时间: 2018-02-08T15:17:50Z
项目社区:https://github.com/leonardoxh/livedata-call-adapter

开源协议:Apache License 2.0

下载


Android Arsenal
Build Status

LiveData Call Adapter for Retrofit

A Retrofit 2 CallAdapter.Factory for Android LiveData

Usage

Add LiveDataCallAdapterFactory as a Call adapter when building your Retrofit instance:

  1. Retrofit retrofit = new Retrofit.Builder()
  2. .baseUrl("https://example.com")
  3. .addCallAdapterFactory(LiveDataCallAdapterFactory.create())
  4. .addConverterFactory(LiveDataResponseBodyConverterFactory.create())
  5. .addConverterFactory(YourConverterFactory.create())
  6. .build();

Your service methods can now use LiveData as their return type, but, note that we also have
a LiveDataResponseBodyConverterFactory this wrapper is necessary when you have a converter
that touch on the return type like moshi or gson, to bypass the Resource<T> class
and give to the Converter.Factory the correct type to serialize.

  1. public interface SuperService {
  2. @GET("/pimba") LiveData<Resource<Pimba>> getPimba();
  3. @GET("/pimba") LiveData<Response<Resource<Pimba>>> getPimbas();
  4. }

Please note the usage of the Resource object, it is required to provide the
error callback to the LiveData object, so when you want verify what is happening
on your network call for example:

  1. retrofit.create(SuperService.class)
  2. .getPimba()
  3. .observe(this, new Observer<Resource<Pimba>>() {
  4. @Override
  5. public void onChange(Resource<Pimba> resource) {
  6. if (resource.isSuccess()) {
  7. //doSuccessAction with resource.resource
  8. } else {
  9. //doErrorAction with resource.error
  10. }
  11. }
  12. })

Gradle dependency

  1. dependencies {
  2. implementation "com.github.leonardoxh:retrofit2-livedata-adapter:1.1.2"
  3. }

Inspiration

License

  1. Copyright 2018 Leonardo Rossetto
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.