A
A
Alexey_soloviev2021-04-18 23:04:02
Android
Alexey_soloviev, 2021-04-18 23:04:02

How to properly pass error information from ViewModel to Activity?

Tell me how to correctly transfer error information from the ViewModel to the Activity? Pass callBack to ViewModel, is this the right solution?

public class MainViewModel extends ViewModel {

    private final MutableLiveData<ArrayList<UserObject>> liveData = new MutableLiveData<>();

    public LiveData<ArrayList<UserObject>> getLiveData() {
        return liveData;
    }

    public void getUserList() {
        new UserRepository().getUserList(new RepositoryCallBack.UserGetList() {
            @Override
            public void onResponse(ArrayList<UserObject> userObject) {
                liveData.setValue(userObject);
            }

            @Override
            public void onError(int statusCode) {
                //Информациб об ошибки необходимо передать в активити (View)
            }
        });
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-04-19
@Alexey_soloviev

I would say exactly the same as success information.
If there was a normal Kotlin, I would advise wrapping this same UserObject in a sealed class:

sealed class Result {
    data class Ok(val data: UserObject): Result()
    data class Error(val statusCode: Int): Result()
}

It will be verbose with Java, but it can also be roughly depicted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question