If you have a Struct as Model or ViewModel and you need to update your SwiftUI View here it is how to do just that with SwiftUI + Combine.
import Combine
struct ViewModel {
var textChangedPublisher: AnyPublisher<String, Never> {
textChangedSubject.eraseToAnyPublisher()
}
private let textChangedSubject = PassthroughSubject<String, Never>()
func triggerUpdate() {
let newStr = DateFormatter().string(from: Date())
textChangedSubject.send(newStr)
}
}
And a screen:
import SwiftUI
struct ContentView: View {
private let vieModel = ViewModel()
@State private var title = "Let's start"
var body: some View {
VStack {
Text(title)
Button.init("Show cuurent date") {
vieModel.triggerUpdate()
}
.onReceive(vieModel.textChangedPublisher) { newValue in
title = newValue
}
}
.padding()
}
}
2
solved SwiftUI – how to observe(.sink/ .onReceive) PassthroughSubject inside a View [closed]