我一直在尝试使用Android中的单个按钮和merge()
将订阅切换为我boolean mSubsciptionToggle
的2个Observable。首次创建片段时,切换设置为false
。
我正在使用Observable.create()
自己创建Observable,看起来像这样:
Observable<String> observable = Observable.create(observer -> {
final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Log incoming broadcasts
}
};
getActivity().registerReceiver(receiver, filter);
if (mSubscriptionToggle) {
observer.onComplete();
}
});
然后我将OnClickListener
添加到按钮中,如下所示:
mStickyButton.setOnClickListener( (View view) -> {
// Observables were created from the first code snippet
Observable.merge(mBatteryObservable, mAirplaneModeObservable)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(// Logging each emitted String);
// Toggling the subscription each time the button is clicked
mSubscriptionToggle = !mSubscriptionToggle;
}
);
我的问题是:第一次单击该按钮时,onComplete()
立即发生。但是,在发生这种情况之前,我打电话给subscribe()
:
mSubscriptionToggle = !mSubscriptionToggle
为什么我打电话给subscribe()
之后布尔值会发生变化?