swift:一个监听类属性/数据变化的Observable, 简单实现.

在开发中, 往往会有这样的需求, 我们需要监听到一个属性值的变化, 或者一个模型的变化, 假如有新值时, 希望能够通知我.所以这篇文章探讨下如何利用定义的Observable类,实现简单的监听.之后demo会放到gitHub.

希望使用,这样就可以监听到新值与老值

属性值.onSet { (oldValue, newValue) in
            print("oldValue:\(oldValue)  newValue:\(newValue)")
 }
  • 我们上代码吧, 定义的Observable类就不多说了,有兴趣的朋友可以看一下代码,不是很难理解.

Observable

import Foundation

protocol AnyObserver: class {
    func remove()
}

struct ObserverOptions: OptionSet {
    typealias RawValue = Int
    let rawValue: Int
    // 如果連續執行, 只執行最後一個,默認方式,也是建議的
    static let Coalescing = ObserverOptions(rawValue: 1)
    // 同步執行, 會等上一個執行完成才執行下一個
    static let FireSynchronously = ObserverOptions(rawValue: 1 << 1)
    // 立即執行, 會監聽到最開始的賦值, 不會等上一個執行完成才執行下一個
    static let FireImmediately = ObserverOptions(rawValue: 1 << 2)
}

//MARK: Observer
class Observer {
    typealias ActionType = (_ oldValue: Value, _ newValue: Value) -> Void
    let action: ActionType
    let queue: OperationQueue
    let options: ObserverOptions
    fileprivate var coalescedOldValue: Value?
    fileprivate var fireCount = 0
    fileprivate weak var observable: Observable?

    init(queue: OperationQueue = OperationQueue.main,
        options: ObserverOptions = [.Coalescing],
        action: @escaping ActionType) {
        self.action = action
        self.queue = queue

        var optionsCopy = options
        if optionsCopy.contains(ObserverOptions.FireSynchronously) {
            optionsCopy.remove(.Coalescing)
        }
        self.options = optionsCopy
    }

    func fire(_ oldValue: Value, newValue: Value) {
        fireCount += 1
        let count = fireCount
        if options.contains(.Coalescing) && coalescedOldValue == nil {
            coalescedOldValue = oldValue
        }

        let operation = BlockOperation(block: { () -> Void in
            if self.options.contains(.Coalescing) {
                guard count == self.fireCount else { return }
                self.action(self.coalescedOldValue ?? oldValue, newValue)
                self.coalescedOldValue = nil
            } else {
                self.action(oldValue, newValue)
            }
        })
        queue.addOperations([operation], waitUntilFinished: self.options.contains(.FireSynchronously))
    }


}

extension Observer: AnyObserver {
    func remove() {
        observable?.removeObserver(self)
    }
}

protocol ObservableType {
    associatedtype ValueType
    var value: ValueType { get }
    func addObserver(_ observer: Observer)
    func removeObserver(_ observer: Observer)
}

extension ObservableType {
    @discardableResult func onSet(_ options: ObserverOptions = [.Coalescing],
        action: @escaping (ValueType, ValueType) -> Void) -> Observer {
        let observer = Observer(options: options, action: action)
        addObserver(observer)
        return observer
    }
}

class Observable {
    var value: Value {
        didSet {
            privateQueue.async {
                for observer in self.observers {
                    observer.fire(oldValue, newValue: self.value)
                }
            }
        }
    }
    fileprivate let privateQueue = DispatchQueue(label: "Observable Global Queue", attributes: [])
    fileprivate var observers: [Observer] = []
    init(_ value: Value) {
        self.value = value
    }
}

extension Observable: ObservableType {
    typealias ValueType = Value
    func addObserver(_ observer: Observer) {
        privateQueue.sync {
            self.observers.append(observer)
        }
        if observer.options.contains(.FireImmediately) {
            observer.fire(value, newValue: value)
        }
    }

    func removeObserver(_ observer: Observer) {
        privateQueue.sync {
            guard let index = self.observers.index(where: { observer === $0 }) else { return }
            self.observers.remove(at: index)
        }
    }
}

*主要将我的Observable.swift 拉进工程就可以用.下面我们讲讲如何使用,有一点必须要提醒一下, 要监听的值必须是同一个对象,这是前提.

  • 假如这里我们想监听到AppSettings的language 变化
import Foundation
class AppSettings: NSObject {
    
    enum Language: String {
        case Chinese = "zh"
        case English = "en"
    }

    let observableLanguage: Observable
    var language: Language {
        get {
            return observableLanguage.value
        }
        set {
            observableLanguage.value = newValue
        }
    }
    
    override init() {
        
        // init
        let language: Language =  .Chinese
        observableLanguage = Observable(language)
        
        super.init()
    }
    
    fileprivate static let kSharedSettingsKey = "defaultUserSettings"
    
    static let shared: AppSettings = {
        let appSettings: AppSettings
        if let savedData = UserDefaults.standard.object(forKey: AppSettings.kSharedSettingsKey) as? Data,
            let defaultSettings = NSKeyedUnarchiver.unarchiveObject(with: savedData) as? AppSettings{
            appSettings = defaultSettings
        } else {
            appSettings = AppSettings()
        }
        
        return appSettings
    }()
    
    static func saveSharedInstance() {
        let data = NSKeyedArchiver.archivedData(withRootObject: AppSettings.shared)
        UserDefaults.standard.set(data, forKey: AppSettings.kSharedSettingsKey)
    }
    
}
  • viewDidLoad 中的使用, 当language变化时它会监听到.
 let appSettings = AppSettings.shared
        let appSettingObserver = appSettings.observableLanguage.onSet { (oldValue, newValue) in
            print("oldValue:\(oldValue)  newValue:\(newValue)")
        }
//最后deinit 时再remove observer

更详细的使用请看我的 gitHubDemo

你可能感兴趣的:(swift:一个监听类属性/数据变化的Observable, 简单实现.)