Last active
October 6, 2022 16:30
-
-
Save smokyonion/d8d9ed1fc53cfcfe89c94df35e19cb3d to your computer and use it in GitHub Desktop.
Observe Properties of Element in Swift.Array using ReactiveSwift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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