Subscribe to the state changes outside of the view
velocityzen opened this issue · comments
Alexey Novikov commented
Is there a way to subscribe to the state changes for example in window class to show/hide toolbar items dynamically? Something like:
state.subscribe {state in
if (state.showToolbar) {
self.showToolbar()
}
}
Rusty Zarse commented
Here is an example using Combine to subscribe to the store's observable state.
don't forget to import Combine
In this example, today
is just a variable on the root AppState. Substitute showToolbar
from your state implementation. Note that the subscription happens in sceneDidBecomeActive so if there were any changes to state before this event, they would not be sent through the sink Subscriber.
var stateSubscription: AnyCancellable? = nil
func sceneDidBecomeActive(_ scene: UIScene) {
var previousToday = store.state.today
stateSubscription = store.$state.sink{state in
if(state.today != previousToday) {
previousToday = state.today
// do something
}
}
}
func sceneWillResignActive(_ scene: UIScene) {
stateSubscription = nil
}
Alexey Novikov commented
thank you! I'll try it today!
Alexey Novikov commented
It works, thank you a lot!