Skip to content

Instantly share code, notes, and snippets.

@kean
Last active April 19, 2021 13:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kean/838cad5c574a2765ea45decf6e4b1b23 to your computer and use it in GitHub Desktop.
Save kean/838cad5c574a2765ea45decf6e4b1b23 to your computer and use it in GitHub Desktop.
// Version 1: Using initializer directly
struct ContentView: View {
@State var count = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("container: \(count)")
.padding()
.onReceive(timer) { _ in
self.count += 1
}
Subview(count)
}
}
}
struct Subview: View {
@StateObject var foo: Foo
init(_ count: Int) {
_foo = StateObject(wrappedValue: Foo(count))
print("init subview \(count)")
}
var body: some View {
Text("subview: \(foo.count)")
}
}
final class Foo: ObservableObject {
let count: Int
init(_ count: Int) {
self.count = count
print("init foo \(count)")
}
deinit {
print("deinit foo \(count)")
}
}
// Version 2: Using generated initializer
struct ContentView: View {
@State var count = 0
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("container: \(count)")
.padding()
.onReceive(timer) { _ in
self.count += 1
}
Subview(foo: Foo(count))
}
}
}
struct Subview: View {
@StateObject var foo: Foo
var body: some View {
Text("subview: \(foo.count)")
}
}
final class Foo: ObservableObject {
let count: Int
init(_ count: Int) {
self.count = count
print("init foo \(count)")
}
deinit {
print("deinit foo \(count)")
}
}
@kean
Copy link
Author

kean commented Dec 28, 2020

What get printed

init subview 0
init foo 0
init subview 1
init subview 2
init subview 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment