Skip to content

Instantly share code, notes, and snippets.

@bitomule
Created February 28, 2020 08:40
Show Gist options
  • Save bitomule/305f42f768a48464fb5612368c1250a8 to your computer and use it in GitHub Desktop.
Save bitomule/305f42f768a48464fb5612368c1250a8 to your computer and use it in GitHub Desktop.
Draft implementation of a Store in swift
public final class Store<Value: Equatable, Action> {
private let reducer: (inout Value, Action) -> Void
private var _observable: BehaviorSubject<Value>
public var observable: Observable<Value> {
get {
return _observable.distinctUntilChanged()
}
}
private var value: Value {
didSet {
_observable.onNext(value)
}
}
private var disposeBag = DisposeBag()
public init(initialValue: Value, reducer: @escaping (inout Value, Action) -> Void) {
self.reducer = reducer
self.value = initialValue
self._observable = BehaviorSubject(value: value)
}
public func send(_ action: Action) {
self.reducer(&value, action)
}
public func view<LocalValue, LocalAction>(
value toLocalValue: @escaping (Value) -> LocalValue,
action toGlobalAction: @escaping (LocalAction) -> Action
) -> Store<LocalValue, LocalAction> {
let localStore = Store<LocalValue, LocalAction>(
initialValue: toLocalValue(self.value),
reducer: { localValue, localAction in
self.send(toGlobalAction(localAction))
localValue = toLocalValue(self.value)
}
)
self.observable.subscribe(onNext: { [weak localStore] newValue in
localStore?.value = toLocalValue(newValue)
}).disposed(by: disposeBag)
return localStore
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment