PublishSubject:
与普通的Subject不同,在订阅时并不立即触发订阅事件,而是允许我们在任意时刻手动调用onNext,onError(),onCompleted来触发事件。
例1:当一个界面发生改变,通知另一个界面做出响应,以下是两个Fragment之间通讯的Demo
在Activity中:定义好公共的PublishSubject对象
PublishSubject publishSubject = PublishSubject.create();
TopFragment topFragment =new TopFragment(publishSubject);
BottomFragment bottom_Fragment =new BottomFragment(publishSubject);
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.fl_top,topFragment, "top")
.replace(R.id.fl_bottom, bottom_Fragment, "bottom").commit();
TopFragment :
@OnClick(R.id.btn_send)
void sendToBottom(){
String result =et_input.getText().toString().trim();
publishSubject.onNext(result);
}
BottomFragment :
publishSubject.subscribe(new Action1() {
@Override
public void call(String s) {
tv_result.setText(s);
}
});
网友评论