Mohamed Ibrahim
Mohamed Ibrahim

Reputation: 3924

CompineLatest that observe multipe checked buttons Rxjava

I have created custom button, it has inner checked listener and I expose it as an observable with the help of a PublishSubject.

public class SwitchItem extends LinearLayout implements SwitchButton.OnCheckedChangeListener {
    //other fields ...
    private PublishSubject<Boolean> checkedObservable = PublishSubject.create();

//I call this method in each
private void initViews(String itemTitle, String itemStatus, boolean isChecked) {
        //other initializations 
        if (switchButton != null) {
            switchButton.setOnCheckedChangeListener(this);
        }

    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        defaultItemStatusText(isChecked);
        checkedObservable.onNext(isChecked);
    }

    //to get the observable
    public Observable<Boolean> getCheckedObservable() {
        return checkedObservable;
    }

}

in th UI I have multiple buttons of this type, I get all of their observables and use CompineLatest to listen on any change, what I try to achieve is to enable a setting save buttton if anyone of the buttons changed its state.

 Observable.combineLatest(button1, button2,button3,(cheked1, cheked2, cheked3) -> {
boolean isSettingsChanged = false;
isSettingsChanged = checked1 != inital1 || checked2 != inital2 || checked3 != inital3;
return isSettingsChanged;
  }).subscribe(enable -> getView().enableSave(enable));

the problem that I have to change all of the buttons states so compineLatest start to fire its logic. I tried to use setChecked() to give them an initial values, but it doesn't work, it always wait to fire a specific button so it start to work. I don't know where the problem is.

Upvotes: 0

Views: 164

Answers (1)

Kenny Li
Kenny Li

Reputation: 132

Here's how I would approach the problem:

Observable.merge(button1.distinct(), button2.distinct(), button3.distinct())
   .subscribe(ignore -> getView().enableSave(true));

By using .distinct(), you ensure the button only emits when there is a change. If you need to emit when there is a change and matches a certain value, then you'd be looking at .distinct().filter(<Predicate>).

Hope this helps

Upvotes: 0

Related Questions