RxSwift and isSelected property on UIButton

前端 未结 1 391
我在风中等你
我在风中等你 2020-12-29 17:03

I have three buttons and I want them to be selected only one at a time:

and:

etc...

My approach is this:

class MyCo         


        
相关标签:
1条回答
  • 2020-12-29 17:49

    Subject and by extension Variable are most of the time only useful when bridging from imperative to reactive world. Here, you could do without them.

    .do(onNext:) is also a way to perform side effect, something you usually don't want in your reactive code.

    // force unwrap to avoid having to deal with optionals later on
    let buttons = [button1, button2, button3].map { $0! }
    
    // create an observable that will emit the last tapped button (which is
    // the one we want selected)
    let selectedButton = Observable.from(
      buttons.map { button in button.rx.tap.map { button } }
    ).merge()
    
    // for each button, create a subscription that will set its `isSelected`
    // state on or off if it is the one emmited by selectedButton
    buttons.reduce(Disposables.create()) { disposable, button in
        let subscription = selectedButton.map { $0 == button }
          .bindTo(button.rx.isSelected)
    
        // combine two disposable together so that we can simply call
        // .dispose() and the result of reduce if we want to stop all
        // subscriptions
        return Disposables.create(disposable, subscription)
    }
    .addDisposableTo(disposeBag)
    
    0 讨论(0)
提交回复
热议问题