Created
July 31, 2018 18:31
-
-
Save davidliu/6094b5b7953d9574418b708c385fb9b6 to your computer and use it in GitHub Desktop.
This file contains 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.support.annotation.Nullable; | |
import io.reactivex.ObservableTransformer; | |
import lombok.AccessLevel; | |
import lombok.AllArgsConstructor; | |
import lombok.Getter; | |
import lombok.ToString; | |
import retrofit2.HttpException; | |
import retrofit2.Response; | |
/** | |
* Idea comes from: https://tech.instacart.com/lce-modeling-data-loading-in-rxjava-b798ac98d80 | |
* An Lce contains either the loading flag, content, or an error. | |
*/ | |
@ToString | |
@Getter | |
@AllArgsConstructor(access = AccessLevel.PRIVATE) | |
public class Lce<D> { | |
private final boolean error; | |
@Nullable | |
private final Throwable errorData; | |
private final boolean loading; | |
@Nullable | |
private final String loadingSource; | |
@Nullable | |
private final D data; | |
public static <D> Lce<D> error(@Nullable Throwable errorData) { | |
return new Lce<>(true, errorData, false, null, null); | |
} | |
public static <D> Lce<D> loading(@Nullable String source) { | |
return new Lce<>(false, null, true, source, null); | |
} | |
public static <D> Lce<D> data(D data) { | |
return new Lce<>(false, null, false, null, data); | |
} | |
/** | |
* Used to transform a common Observable<Response> retrofit api response | |
* into Observable<Lce> | |
* | |
* @param <D> The data type that the Response and Lce hold. | |
* @return An observable that will emit Lce objects based on the response. | |
*/ | |
public static <D> ObservableTransformer<Response<D>, Lce<D>> transformRequestToLce() { | |
return transformRequestToLce(null); | |
} | |
public static <D> ObservableTransformer<Response<D>, Lce<D>> transformRequestToLce(@Nullable String loadingSource) { | |
return upstream -> upstream | |
.map(response -> response.isSuccessful() ? | |
Lce.data(response.body()) : | |
Lce.<D>error(new HttpException(response))) | |
.startWith(Lce.loading(loadingSource)) | |
.onErrorReturn(Lce::error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment