Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huynguyencong/35af81f6e5f472a45c25429e701bf64d to your computer and use it in GitHub Desktop.
Save huynguyencong/35af81f6e5f472a45c25429e701bf64d to your computer and use it in GitHub Desktop.
Pass dynamic data from parent view to child view in SwiftUI using MVVM architecture.
import SwiftUI
import Combine
struct ContentView: View {
var body: some View {
ParentView()
}
}
struct ParentView: View {
@StateObject var viewModel = ParentViewModel()
var body: some View {
VStack {
Text("Random: \(viewModel.number)")
Button("Random") {
viewModel.random()
}
Divider()
CounterView(random: viewModel.$number.eraseToAnyPublisher())
}
}
}
class ParentViewModel: ObservableObject {
@Published var number: Int = 0
func random() {
number = Int.random(in: 0..<100)
}
}
struct CounterView: View {
@StateObject private var viewModel = CounterViewModel()
let random: AnyPublisher<Int, Never>
var body: some View {
VStack {
Text("Random: \(viewModel.random)")
Text("Count: \(viewModel.count)")
Text("Total: \(viewModel.total)")
Button("Increase") {
viewModel.increase()
}
}
.onReceive(random) { value in
viewModel.random = value
}
}
}
class CounterViewModel: ObservableObject {
init() {
$count
.combineLatest($random)
.map { count, random in
return count + random
}
.assign(to: &$total)
}
@Published var count = 0
@Published var random: Int = 0
@Published var total: Int = 0
func increase() {
count += 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment