使用rxjava进行片段间通信

shi*_*Dev 4 android android-fragments rx-java rx-android

我有一个片段活动.在该片段内部有一个viewpager,里面有一个列表.现在,一旦用户点击列表中的项目,片段应该被另一个片段替换,我需要传递一些数据,如列表位置和链接到该列表的其他一些值.我可以通过使用接口来实现这一点,但是因为我们正在使用rxjava所以想要使用rx来做...不要立即实现事件总线或rxbus模式.那么如何使用rxjava实现它呢?

And*_*dEx 6

一种方法:

/* inside whatever you mean by the list */
PublishSubject<Void> mClickSubject = PublishSubject.create(); //or use another type instead of Void if you need

/*...*/
    item.setOnClickListener(v -> mClickSubject.onNext(null));
/*...*/

public Observable<Void> itemClicked() {
    return mClickSubject;
}

/* pass your subject/observable all the way to the activity */

/* inside the activity */

private void setupSubscription() {
    mCurrentFragment.listItemClicked()
            .subscibe(/* switch fragment */);
}
Run Code Online (Sandbox Code Playgroud)

或者另一种方法是让一个单例/静态类持有一个成员PublishSubject并通过它推送项目.这样做你不需要所有的getter将observable从列表传递给activity.