我有以下通用类:
public class DataOrException<T, E extends Exception> {
public T data;
public E exception;
}
而且我正在从Firebase身份验证,FirebaseUser对象或异常中获取:
MutableLiveData<DataOrException<FirebaseUser, Exception>> signIn(String email, String password) {
MutableLiveData<DataOrException<FirebaseUser, Exception>> liveData = new MutableLiveData<>();
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser firebaseUser = auth.getCurrentUser();
liveData.setValue(firebaseUser);
} else {
liveData.setValue(authTask.getException());
}
});
return liveData;
}
但出现以下错误:
setValue(com.example.DataOrException<com.google.firebase.auth.FirebaseUser, java.lang.Exception>)
in MutableLiveData cannot be applied to (java.lang.Exception)
我应该传递给setValue()以便它不再抱怨吗?
您的MutableLiveData需要一个DataOrException<FirebaseUser, Exception>
类型的值,因此您需要构造一个并传递它。
DataOrException<FirebaseUser, Exception> value = new DataOrException<>()
if (task.isSuccessful()) {
value.data = auth.getCurrentUser();
} else {
value.exception = authTask.getException();
}
liveData.setValue(value);