• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps How to handle errors in LiveData + MVVM + Retrofit?

Nixon3333

Lurker
Nov 5, 2019
1
0
Hi! I have a problem with handling errors from retrofit.
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);
    }
}
Result class:

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;
}
And ViewModel:

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));
}
App crashed with ClassCastException. I know this exception, but don't know how to wrap data correctly?
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones