Install Effect without going through the reducer

I would like to install a long living Publisher right away in the Store (NotificationCenter.Publisher for example).
In the moment, I have to send an action to the viewstore (from onAppear) to get the effect into the store.
Is there an alternative way?

Thank you

PS. I wouldn't need that if I could send actions directly to the store.
.sink { action in
looks wrong

It may look wrong to construct a ViewStore to send actions to it, but it's definitely the way to do this. You could hold onto the view store in your controller/view also:

let store: Store<AppState, AppAction>
let viewStore: ViewStore<AppState, AppAction>

init(store: Store<AppState, AppAction>) { = store
  self.viewStore = ViewStore(

func viewDidLoad() {
  NotificationCenter.default.publisher(for: ...)
    .sink { [weak self] self?.viewStore.send(...) }
    .store(in: &self.cancellables)

This is definitely the most straightforward way for you to have an external event source feed its data into the system.

However, I will also say that executing this effect in the reducer (e.g. using .onAppear as you mentioned) is still most ideal because it allows you to test the full lifecycle of the effect using TestStore, and makes you prove that you cancel this long living effect in the way you expect.


OK, thank you. I will then stick to the onAppear-approach

Terms of Service

Privacy Policy

Cookie Policy