Skip to content

Instantly share code, notes, and snippets.

@atimca
Created June 19, 2020 09:24
Show Gist options
  • Save atimca/68f4167d4809a12d6ac88ddb1a7e92f0 to your computer and use it in GitHub Desktop.
Save atimca/68f4167d4809a12d6ac88ddb1a7e92f0 to your computer and use it in GitHub Desktop.
public func scope<LocalState, LocalEvent: ComponentableEvent>(
state toLocalState: @escaping (State) -> LocalState,
event toGlobalEvent: @escaping (LocalEvent) -> Event,
feedBacks: [SideEffect<LocalState, LocalEvent>]
) -> Store<LocalState, LocalEvent> where LocalEvent.State == LocalState {
let localStore = Store<LocalState, LocalEvent>(
initial: toLocalState(state),
feedBacks: feedBacks,
reducer: { localState, localEvent in
var state = self.state
self.reducer(&state, toGlobalEvent(localEvent))
localState = toLocalState(state)
if localEvent != LocalEvent.updateFromOutside(localState) {
self.accept(toGlobalEvent(localEvent))
}
}
)
$state
.map(toLocalState)
.removeDuplicates()
.sink { [weak localStore] newValue in
localStore?.accept(.updateFromOutside(newValue))
}
.store(in: &localStore.disposeBag)
return localStore
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment