I read this blog post which introduced the new Swift Observations API.
I'm curious if this API allows us to adopt Swift Observation in a custom UIKit paradigm.
Can we observe nested changes?
Here, I've created an ObservableType and a NonObservableType.
Firstly, I'm curious if we can observe changes through a non-observable object.
@Observable
@MainActor
class ObservableType {
var count: Int = 0
}
@MainActor
struct NonObservableType {
let observable: ObservableType
var count: Int {
observable.count
}
func increment() {
observable.count += 1
}
}
Here, I create a stream of observations by returning the nonObservable's count property.
I use a detached task as a psuedo expection.
I then call increment() on the nonObservable struct, and expect the results:
@MainActor
@Test
func observation() async throws {
// Given
let observable = ObservableType()
let nonObservable = NonObservableType(observable: observable)
let stream = Observations {
nonObservable.count
}
let observation = Task.detached {
var values: [Int] = []
for try await count in stream {
values.append(count)
if values.count >= 3 {
break
}
}
return values
}
// When
nonObservable.increment()
await Task.yield()
nonObservable.increment()
await Task.yield()
nonObservable.increment()
await Task.yield()
// Expect
let result = try await observation.value
#expect(result == [1, 2, 3])
}
Surprisingly, this seems to work — tests pass!
This makes me think, we should be able to adopt SwiftUI's data-flow within UIKit by leveraging this new API.