Skip to content

Instantly share code, notes, and snippets.

@smokyonion
Last active October 6, 2022 16:30
Show Gist options
  • Select an option

  • Save smokyonion/d8d9ed1fc53cfcfe89c94df35e19cb3d to your computer and use it in GitHub Desktop.

Select an option

Save smokyonion/d8d9ed1fc53cfcfe89c94df35e19cb3d to your computer and use it in GitHub Desktop.
Observe Properties of Element in Swift.Array using ReactiveSwift
import ReactiveSwift
/// Problem to Solve
class Soldier {
let name: Property<String>
let deployed: MutableProperty<Bool> = MutableProperty(false)
init(_ name: String) {
self.name = Property(value: name)
}
}
let soldiers: MutableProperty<[Soldier] = MutableProperty([Soldier("Tim"), Soldier("Grace")])
let button = UIButton()
button.reactive.isEnabled <~ // as soon as there is one of the Soldiers is deployed, the button should become enabled
/// Solution
let producer = soldiers.producer.flatMap(.latest) {
return SignalProducer.merge($0.map { $0.deployed.producer }).scan(0) {
let count = $0.0 // keeps tracking current number of deployed soldiers
let isDeployed = $0.1
if isDeployed {
return count + 1 // increment the count
} else {
return max(0, count - 1) // decrement the count but don't go below zero
}
}.map { $0 > 0 }.skipRepeats() // is the total deployed soldier count greater than zero?
}
producer.startWithValues { value in
print("is there at least one soldier deployed: ", value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment