-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathLiveData.swift
More file actions
38 lines (31 loc) · 849 Bytes
/
LiveData.swift
File metadata and controls
38 lines (31 loc) · 849 Bytes
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
//
// LiveData.swift
// SwiftWeather
//
// Created by Jake Lin on 22/10/18.
// Copyright © 2018 Jake Lin. All rights reserved.
//
import Foundation
/// `LiveData` is a data holder class that can be observed. It is a simplified version of Android Architecture component `LiveData`
class LiveData<T> {
typealias Observer = (T) -> Void
var observer: Observer?
private var value: T
init(_ value: T) {
self.value = value
}
func observe(_ observer: Observer?) {
self.observer = observer
observer?(value)
}
func setValue(value: T) {
self.value = value
self.observer?(value)
}
func postValue(value: T) {
self.value = value
DispatchQueue.main.async(execute: { [unowned self, value] in
self.observer?(value)
})
}
}