0

I have three btns, select one, and unselect the rest two.

one

The following RXSwift code is not very elegant.

twoBtn.isSelected = true

// the btns
let buttons = [oneBtn, twoBtn, threeBtn]

// find the selected btn we need
let selectedBtn : Observable<UIButton?> = Observable.from(buttons.map({ (button)  in
    return button!.rx.tap.map({
        return button
    })  
})).merge()


//  every btn subscribe to the selectedButton
for buttonPiece in buttons{
    selectedBtn.map { (btn) in
        return btn == buttonPiece
        }.bind(to: buttonPiece!.rx.isSelected).disposed(by: disposeBag)
}

The BehaviorSubject starts with an initial value, and they will replay the latest value or the initial value.

I think BehaviorSubject is proper here.

new to RxSwift, How to do it better?

black_pearl
  • 2,549
  • 1
  • 23
  • 36
  • 1
    This question belongs on (https://codereview.stackexchange.com) which is for code that needs to be made "more elegant." :-) – Daniel T. Nov 01 '18 at 11:44

1 Answers1

0

Define a State struct with states of all buttons in it, modify it by using .scan() operator like let state: Observable<State> = events.scan(State()) { oldState, event) -> State in /* update and return state */ } and subscribe every button to it like state.map { $0.button1state }.

Maxim Volgin
  • 3,957
  • 1
  • 23
  • 38