Sobes.tech
Junior — Middle

How is data exchanged between modules in SwiftUI using Combine?

sobes.tech AI

Answer from AI

In SwiftUI using Combine, data exchange between modules is usually carried out through reactive data streams and state binding. Main approaches:

  • ObservableObject and @Published: a class implementing the ObservableObject protocol is created, and properties that need to be tracked are marked with @Published. Other modules subscribe to changes via @ObservedObject or @StateObject.

  • PassthroughSubject and CurrentValueSubject: for transmitting events or values between modules without direct connection.

Example:

import SwiftUI
import Combine

class UserSettings: ObservableObject {
    @Published var username: String = ""
}

struct ContentView: View {
    @StateObject var settings = UserSettings()

    var body: some View {
        VStack {
            TextField("Username", text: $settings.username)
            ProfileView(settings: settings)
        }
    }
}

struct ProfileView: View {
    @ObservedObject var settings: UserSettings

    var body: some View {
        Text("Hello, \(settings.username)!")
    }
}

Thus, changes in one module automatically reflect in another through Combine and SwiftUI.

How is data exchanged between modules in SwiftUI… - sobes.tech