我正在尝试使用 Mosby 和 EventBus 开发应用程序。我想要的第一个事件是在用户登录之后,创建一个粘性事件,以便每个屏幕都可以随时访问登录信息。
根据 Mosby 邮件示例,我有一个这样的 BasePresenter:
public abstract class EventBusPresenter<V extends MvpView> extends MvpBasePresenter<V> {
private static final java.lang.String TAG = tag(EventBusPresenter.class);
@Inject
protected EventBus mEventBus;
LoginSuccessfulEvent userInfo;
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onLoginSuccessful(LoginSuccessfulEvent event) {
MCLog.i(TAG, "Received a login event!");
userInfo = event;
onLoginReceived(event);
}
protected abstract void onLoginReceived(LoginSuccessfulEvent e);
public LoginSuccessfulEvent getUserInfo(){
return userInfo;
}
@Override
public void attachView(V view) {
super.attachView(view);
mEventBus.register(this);
}
@Override
public void detachView(boolean retainInstance) {
super.detachView(retainInstance);
mEventBus.unregister(this);
}
}
当用户登录时,我使用此代码:
public void doLogin(String username, String password) {
if (isViewAttached()) {
getView().showLoading();
}
cancelSubscription();
mSubscriber = new Subscriber<AuthenticationResponse>() {
@Override
public void onCompleted() {
if (isViewAttached()) {
getView().loginSuccessful();
}
}
@Override
public void onError(Throwable e) {
if (isViewAttached()) {
getView().showLoginError();
}
}
@Override
public void onNext(AuthenticationResponse authenticationResponse) {
User user = authenticationResponse.getUser();
MCLog.w(TAG, String.format("Login was successful with user: %s", user) );
mEventBus.postSticky(new LoginSuccessfulEvent(user, authenticationResponse.getToken()));
String token = authenticationResponse.getToken();
MCLog.i(TAG, String.format("Token obtained = %s", token));
mSharedPreferences.edit().putString(PreferenceKeys.TOKEN_KEY, token).apply();
}
};
我的想法是,对于每个屏幕,一旦加载它就可以通过 EventBus 订阅检索 UserInfo。
问题是——这个事件也来了,儿子。根据 mosby 自己的 BaseFragment 类,我这样做:
public abstract class BaseFragment<V extends MvpView, P extends MvpPresenter<V>> extends MvpFragment<V, P> {
private Unbinder mUnbinder;
@LayoutRes
protected abstract int getLayoutRes();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
return inflater.inflate(getLayoutRes(), container, false);
}
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
inject();
super.onViewCreated(view, savedInstanceState);
mUnbinder = ButterKnife.bind(this, view);
}
@Override public void onDestroyView() {
super.onDestroyView();
mUnbinder.unbind();
}
/**
* Inject dependencies
*/
protected void inject() {
}
}
这意味着注入在视图创建之前到达,所以每当我尝试响应接收到的 LoginEvent 时,需要更新的 UI 元素不再存在。
我怎样才能做到这一点?这甚至是正确的方法吗?