I have the following requirements in my SwiftUI view:
- Have 2 toggles on screen
- Based on the values of those toggles, I need to calculate a state (1 value)
- When that state changes, I need to post it to a server
- When the view appears, I have to set the toggles according to the last state stored locally
- At some point I have to request the state from the server and update the toggles accordingly.
Here is my code (in an observable object):
@Published var toggleValue1: Bool = false
@Published var toggleValue2: Bool = false
init() {
toggleValue1 = getValue1()
toggleValue2 = getValue2()
cancellable = $toggleValue1
.combineLatest($toggleValue2)
.map { ... } // Transforms (bool, bool) to SomeType
.removeDuplicates()
.dropFirst()
.sink { ... } // Upload to backend. Starts a Task
}
Now the combination of .dropFirst
and the fact that my upload task verifies if the value to be uploaded is different from what is stored locally (which should also be on the server) solves that I’m not uploading values when the view appears but the issue is with #5. When I’m updating those @Published
variables to update the UI, they also trigger an upload.
I’m trying to think of any other combination of publishers or bindings to ignore programatic changes but I can’t find any. I think I could set a flag to ignore the following N events, but its seems very hacky