Dimillian / SwiftUIFlux

A very naive implementation of Redux using Combine BindableObject to serve as an example

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Subscribe to the state changes outside of the view

velocityzen opened this issue · comments

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()
  }
}

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
    }

thank you! I'll try it today!

It works, thank you a lot!