swift property observer for data processing

88 Views Asked by At

How can I get notified when data has changed to process it? I have a simple code for easy to understand what I want:

class Data {
    var data: [Int] = [] {
        didSet {
            print("changed")
        }
    }
}

class Process {
    var data: Data
    
    init(data: Data) {
        self.data = data
    }
    
    func processIfChanged() {
        //how to run this code?
    }
}

class Global {
    var data: [Data] = []
    var process: [Process] = []
}

let global = Global()
global.data = [Data()]
global.process = [Process(data: global.data.first!)]

global.data.first!.data.append(1)
global.data.first!.data.append(5)
1

There are 1 best solutions below

0
ChanOnly123 On

Can try this using Combine module

import Combine

class Data {
    let subject = CurrentValueSubject<Int, Never>(5)

    var data: [Int] = [] {
        didSet {
            print("changed")
            subject.send(1)
        }
    }
}

class Process {
    var dataSubject: AnyCancellable?
    var data: Data {
        didSet {
            registerObserver()
        }
    }
    
    init(data: Data) {
        self.data = data
        registerObserver()
    }
    
    func registerObserver() {
        dataSubject = data.subject.dropFirst().sink { [unowned self] _ in
            self.processIfChanged()
        }
    }
    
    func processIfChanged() {
        print("how to run this code?")
    }
}