Created
August 25, 2018 13:23
-
-
Save abhinav272/42f7af5c56f316532809f9c922e963fb to your computer and use it in GitHub Desktop.
MediatorLiveData for retrofit response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.arch.lifecycle.MediatorLiveData; | |
import android.arch.lifecycle.MutableLiveData; | |
import android.arch.lifecycle.Observer; | |
import com.abhinav.basemvvmsample.data.model.FailureResponse; | |
import java.net.SocketTimeoutException; | |
import java.net.UnknownHostException; | |
import retrofit2.Call; | |
import retrofit2.Callback; | |
import retrofit2.Response; | |
public abstract class CustomApiCallback<T> extends MediatorLiveData<T> implements Callback<T> { | |
private MutableLiveData<FailureResponse> failureLiveData; | |
private MutableLiveData<Boolean> noNetworkLiveData; | |
private MutableLiveData<Throwable> errorLiveData; | |
private void initLiveData() { | |
failureLiveData = new MutableLiveData<>(); | |
noNetworkLiveData = new MutableLiveData<>(); | |
errorLiveData = new MutableLiveData<>(); | |
} | |
protected abstract Observer<Boolean> getNoNetworkObserver(); | |
protected abstract Observer<FailureResponse> getFailureObserver(); | |
protected abstract Observer<Throwable> getErrorObserver(); | |
@Override | |
protected void onInactive() { | |
super.onInactive(); | |
removeSource(failureLiveData); | |
removeSource(noNetworkLiveData); | |
removeSource(errorLiveData); | |
} | |
@Override | |
protected void onActive() { | |
super.onActive(); | |
initLiveData(); | |
addSource(failureLiveData, getFailureObserver()); | |
addSource(noNetworkLiveData, getNoNetworkObserver()); | |
addSource(errorLiveData, getErrorObserver()); | |
} | |
@Override | |
public void onResponse(Call<T> call, Response<T> response) { | |
if (response.isSuccessful()) { | |
setValue(response.body()); | |
} else { | |
failureLiveData.setValue(getFailureErrorBody(call.request().url().url().getFile(), response)); | |
} | |
} | |
@Override | |
public void onFailure(Call<T> call, Throwable t) { | |
if (t instanceof SocketTimeoutException || t instanceof UnknownHostException) { | |
noNetworkLiveData.setValue(true); | |
} else { | |
errorLiveData.setValue(t); | |
} | |
} | |
/** | |
* Create your custom failure response out of server response | |
* Also save Url for any further use | |
*/ | |
protected final FailureResponse getFailureErrorBody(String url, Response<T> errorBody) { | |
FailureResponse failureResponse = new FailureResponse(); | |
failureResponse.setErrorMessage(errorBody.message()); | |
failureResponse.setErrorCode(errorBody.code()); | |
return failureResponse; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment