Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. public typealias Reducer<Value, Action, Effect> = (inout Value, Action) -> Command<Effect>
  2.  
  3. public final class Store<Value, Action>: ObservableObject {
  4. //private let reducer: (inout Value, Action) -> Void
  5. private var _send: ((Action) -> Void)?
  6. @Published public private(set) var value: Value
  7. private var cancellable: Cancellable?
  8.  
  9. // the reducer for the main Store needs to be generic on <Value, Action, Action>,
  10. // but other reducers are generic on <Value, Action, Effect>
  11. public init(initialValue: Value, reducer: @escaping Reducer<Value, Action, Action>) {
  12. self.value = initialValue
  13. self._send = { action in
  14. let command = reducer(&self.value, action)
  15. // TODO do something with the command in the runtime...
  16. }
  17. }
  18.  
  19. private init(initialValue: Value, send: @escaping (Action) -> Void) {
  20. self.value = initialValue
  21. self._send = send
  22. }
  23.  
  24. public func send(_ action: Action) {
  25. self._send?(action)
  26. }
  27.  
  28. public func view<LocalValue, LocalAction>(
  29. value toLocalValue: @escaping (Value) -> LocalValue,
  30. action toGlobalAction: @escaping (LocalAction) -> Action
  31. ) -> Store<LocalValue, LocalAction> {
  32.  
  33. let localStore = Store<LocalValue, LocalAction>(
  34. initialValue: toLocalValue(self.value),
  35. send: { action in
  36. self.send(toGlobalAction(action))
  37. })
  38. localStore.cancellable = self.$value.sink { [weak localStore] newValue in
  39. localStore?.value = toLocalValue(newValue)
  40. }
  41.  
  42. return localStore
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement