Search code examples
swiftfrpreactivekitswiftbond

Swift Bond framework - many to one relationship - trigger a single command if anything changes


Consider the following example:

Given a set of observables:

let value1 = Observable(false)
let value2 = Observable(false)
let value3 = Observable(false)

let isSaveButtonEnabled = Observable(false)

I'd like to execute this code every time something changes:

func validate() {
{...}
isSaveButtonEnabled.value = true
}

Currently, the only way to configure such relationship is to individually add a closure to every Observable:

value1.onNext {
self.validate()
}

value2.onNext {
self.validate()
}

....

The goal:

I'd like to program it using syntax similar to this:

[value1, value2, value.....].onAnyChange {
self.validate()
}

Solution

  • Something I came up:

    private func configureValidationLogic() {
        [vaule1.eraseType(), 
         vaule2.eraseType(),
        vaule3.eraseType(),
        vaule4.eraseType(),
        vaule5.eraseType()].forEach { (signal) in
            signal.observeNext { [weak self] in
                guard let self = self else {return}
                self.validate()
            }
        }
    }
    

    Maybe, there is a better (built-in into the library) approach of achieving the same.