Peter London
Peter London

Reputation: 81

RxSwift How to add "clear all" UIButton to simple spreadsheet example

Here's the code from the RxSwift repo for a simple spreadsheet (adding three numbers):

Observable.combineLatest(number1.rx_text, number2.rx_text, number3.rx_text) { textValue1, textValue2, textValue3 -> Int in
        return (Int(textValue1) ?? 0) + (Int(textValue2) ?? 0) + (Int(textValue3) ?? 0)
    }
    .map { $0.description }
    .bindTo(result.rx_text)
    .addDisposableTo(disposeBag)

I want to add a "Clear all" UIButton, that will cause the three boxes to be reset to zero and the total also set to zero. In imperative style, very easy.

What is the correct way of adding this button in RxSwift?

Upvotes: 1

Views: 1147

Answers (1)

solidcell
solidcell

Reputation: 7739

Here are a couple of ways off the top of my head.

Imperative

button.rx_tap
    .subscribeNext { [weak self] _ in
        self?.number1.text = ""
        self?.number2.text = ""
        self?.number3.text = ""
    }
    .addDisposableTo(disposeBag)

Note however, that this will not update the combineLatest Observable below until you change focus between fields. I haven't looked into why.

Using Variables

// Declared as a property
let variable1 = Variable<String>("")

// Back down in `viewDidLoad`
number1.rx_text
    .bindTo(variable1)
    .addDisposableTo(disposeBag)

variable1.asObservable()
    .bindTo(number1.rx_text)
    .addDisposableTo(disposeBag)

button.rx_tap
    .subscribeNext { [weak self] _ in
        self?.variable1.value = ""
        // and other variables as well..
    }
    .addDisposableTo(disposeBag)

Observable.combineLatest(variable1.asObservable(), ....

I've omitted showing the same code for variable2 and variable3, as you should probably make a two-way binding helper method if you go this route.

Upvotes: 1

Related Questions