Android Java中如何从EventObserver获取返回结果?
如何在EventObserver回调中获取data的具体值?
我已经实现了Event和EventObserver类,在Repository中通过MutableLiveData发送了包裹UserModel的Event对象,但在ViewModel中观察时,不知道怎么获取回调里的data值。
已实现的Event类
public class Event<T> { private boolean hasBeenHandled = false; private T content; public Event(T content) { this.content = content; } public T getContentIfNotHandled() { if (hasBeenHandled) { return null; } else { hasBeenHandled = true; return content; } } public boolean isHandled() { return hasBeenHandled; } }
已实现的EventObserver类
import androidx.annotation.Nullable; import androidx.lifecycle.Observer; public class EventObserver<T> implements Observer<Event<T>> { private OnEventChanged onEventChanged; public EventObserver(OnEventChanged onEventChanged) { this.onEventChanged = onEventChanged; } @Override public void onChanged(@Nullable Event<T> tEvent) { if (tEvent != null && tEvent.getContentIfNotHandled() != null && onEventChanged != null) onEventChanged.onUnhandledContent(tEvent.getContentIfNotHandled()); } interface OnEventChanged<T> { void onUnhandledContent(T data); } }
Repository中的代码
private MutableLiveData<Event<String>> _amsRepositoryError = new MutableLiveData<>(); public MutableLiveData<Event<UserModel>> amsLoginSuccessReply(){return _amsLoginSuccessReply;} _amsLoginSuccessReply.postValue(new Event(userModel));
ViewModel中的观察代码(问题所在)
amsRepository.amsLoginSuccessReply().observe(mLifeCycleOwner, new EventObserver<UserModel>(data -> { // 如何获取这里的data值? }));
解决方案
你其实已经拿到了目标数据,lambda表达式里的data就是Event包裹的UserModel实例,直接使用它的属性或调用方法即可:
amsRepository.amsLoginSuccessReply().observe(mLifeCycleOwner, new EventObserver<UserModel>(data -> { // 示例:获取UserModel中的用户名属性 String userName = data.getUserName(); // 示例:调用处理登录成功的方法,传入data processLoginSuccess(data); }));
原理说明:EventObserver内部会调用Event的getContentIfNotHandled()获取未处理的内容,然后通过OnEventChanged接口的onUnhandledContent方法把UserModel对象传递到lambda回调中,所以直接使用参数data就能拿到具体值。
内容的提问来源于stack exchange,提问作者Ibanez1408
相关产品推荐
相关产品推荐

