2015-11-29 52 views
3

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

回答

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,并通过它推项目。这样做,你不需要所有的getters将列表中的observable传递给activity。

+1

你可以用例子解释第二个单例方法吗? – shivamDev

+1

@shivamDev我想你正在寻找这样的东西:https://stackoverflow.com/a/40836109/1101730 – Micer