Wednesday, February 8, 2023
HomeiOS Developmentios - SwiftUI - observe(.sink/ .onReceive) PassthroughSubject inside a View

ios – SwiftUI – observe(.sink/ .onReceive) PassthroughSubject inside a View


If in case you have a Struct as Mannequin or ViewModel and it’s good to replace your SwiftUI View right here it’s just do that with SwiftUI + Mix.

import Mix

struct ViewModel {

    var textChangedPublisher: AnyPublisher<String, By no means> {
        textChangedSubject.eraseToAnyPublisher()
    }
    non-public let textChangedSubject = PassthroughSubject<String, By no means>()

    func triggerUpdate() {
        let newStr = DateFormatter().string(from: Date())
        textChangedSubject.ship(newStr)
    }

}

And a display screen:

import SwiftUI

struct ContentView: View {
    
    non-public let vieModel = ViewModel()
    @State non-public var title = "Let's begin"
    
    var physique: some View {
        VStack {
            Textual content(title)
            Button.init("Present cuurent date") {
                vieModel.triggerUpdate()
            }
            .onReceive(vieModel.textChangedPublisher) { newValue in
                title = newValue
            }
        }
        .padding()
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments