forked from kudoleh/iOS-Clean-Architecture-MVVM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Observable.swift
executable file
·41 lines (32 loc) · 963 Bytes
/
Observable.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//
// Observable.swift
// ExampleMVVM
//
// Created by Oleh Kudinov on 16.02.19.
//
import Foundation
public final class Observable<Value> {
struct Observer<Value> {
weak var observer: AnyObject?
let block: (Value) -> Void
}
private var observers = [Observer<Value>]()
public var value: Value {
didSet { notifyObservers() }
}
public init(_ value: Value) {
self.value = value
}
public func observe(on observer: AnyObject, observerBlock: @escaping (Value) -> Void) {
observers.append(Observer(observer: observer, block: observerBlock))
observerBlock(self.value)
}
public func remove(observer: AnyObject) {
observers = observers.filter { $0.observer !== observer }
}
private func notifyObservers() {
for observer in observers {
DispatchQueue.main.async { observer.block(self.value) }
}
}
}