I'm trying to incorporate Combine in a current project, and I am not sure if the current approach is the best/most idiomatic way to do it.
So far I have a parent object which has a shared state with some child objects, and the state is being shared as a CurrentValueSubject:
class Child {
var state: CurrentValueSubject<SharedState, Never>
init(_ state: CurrentValueSubject<SharedState, Never>) {
self.state = state
state.sink { value in self.doSomething(value) }
}
}
class Parent {
var state: CurrentValueSubject<SharedState, Never> =
let child1: Child
let child2: Child
init() {
let state = CurrentValueSubject<SharedState, Never>(SharedState())
self.state = state
self.child1 = Child(state: state)
self.child2 = Child(state: state)
}
...
}
So the goal is that the parent, child1 and child2 should each be able to update the shared state, and the other components should be able to observe and respond to the value change.
I believe the current implementation should work, but is there a better/more idiomatic way to implement this?
note: I this is not in the context of SwiftUI