使用rxjava进行片段间通信

时间:2015-11-29 11:15:56

标签: android android-fragments rx-java rx-android

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

1 个答案:

答案 0 :(得分: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 */);
}

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

相关问题