Nixon3333
Lurker
Hi! I have a problem with handling errors from retrofit.
MainActivity:
Result class:
And ViewModel:
App crashed with ClassCastException. I know this exception, but don't know how to wrap data correctly?
MainActivity:
Java:
private void initRecyclerView() {
mProgressDialog = new ProgressDialog(this);
recyclerView = binding.rvTasks;
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new TaskAdapter();
recyclerView.setAdapter(adapter);
LiveData<Result<List<Task>>> result = viewModel.getTasks();
result.observe(this, tasks -> handleTasks(tasks));
}
private void handleTasks(Result<List<Task>> tasks) {
if (tasks.getError() != null)
adapter.setTaskCollection(tasks.getResult());
else {
List<Task> list = new ArrayList<>();
list.add(0, new Task(1, 1, "Title", "Body"));
adapter.setTaskCollection(list);
}
}
Java:
public class Result<T> {
private final T result;
private final Throwable error;
private Result(@Nullable T result, @Nullable Throwable error) {
this.result = result;
this.error = error;
}
@NonNull
public static <T> Result<T> success(@NonNull T result) {
return new Result(result, null);
}
@NonNull
public static <T> Result<T> error(@NonNull Throwable error) {
return new Result(null, error);
}
@Nullable
public T getResult() {
return result;
}
@Nullable
public Throwable getError() {
return error;
}
Code:
public LiveData getTasks() {
return LiveDataReactiveStreams.fromPublisher(
Observable.just(retrofitApi.getTasks()
.map(Result::success)
.onErrorReturn(Result::error)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()))
.toFlowable(BackpressureStrategy.MISSING));
}