If you can move the code generation into the ObservableObject
itself, that would be the easiest:
class RootState : ObservableObject {
@Published var result : String = ""
private var cancellables = Set<AnyCancellable>()
init() {
Timer.publish(every: 1, on: .main, in: .default)
.autoconnect()
.sink { (_) in
//perform some expensive calculation here
self.result = "(Date().timeIntervalSince1970)"
}
.store(in: &cancellables)
}
}
struct CodeGenerationView: View {
@StateObject var root: RootState
var body: some View {
Text(root.result)
}
}
Note that I'm using Combine to connect the timer publisher. If for some reason you couldn't do your code generation inside your RootState, using Combine to connect Publishers together is probably the way to go. You almost certainly won't actually need it in this case, but there's even a throttle
method: https://developer.apple.com/documentation/combine/fail/throttle(for:scheduler:latest:)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…