Skip to content

Instantly share code, notes, and snippets.

@davidliu
Created January 22, 2018 01:00
Show Gist options
  • Save davidliu/44954cbe8c2c161e9143eb6fdac83c0b to your computer and use it in GitHub Desktop.
Save davidliu/44954cbe8c2c161e9143eb6fdac83c0b to your computer and use it in GitHub Desktop.
Loading/Content/Error object for RxJava
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&lt;Response&gt; retrofit api response
* into Observable&lt;Lce&gt;
*
* @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