I am trying out this quick start for SwiftUI and Combine in order to try and understand how to connect my Realm database to Combine.
The example observes a RealmSwift.List
and keeps a table populated with its data. This is is a linked list to a child class. I'm wondering how to observe a Results
collection so I can keep track of any changes to an entire Realm class.
For example, let's say I have a Workspace
class:
class Workspace: Object, ObjectKeyIdentifiable{
@objc dynamic var id = UUID().uuidString
@objc dynamic var name = ""
@objc dynamic var archived = false
}
In the state object, I can set up a Results<Workspace>
variable like this:
class AppState: ObservableObject {
@Published var workspaces: Results<Workspace>?
var cancellables = Set<AnyCancellable>()
init(){
let realmPublisher = PassthroughSubject<Realm, Error>()
realmPublisher
.sink(receiveCompletion: { _ in }, receiveValue: { realm in
//Get the Results
self.workspaces = realm.objects(Workspace.self)
})
.store(in: &cancellables)
realmPublisher.send(try! Realm())
return
}
}
But when it comes time to observe the object, I can't because Results
isn't an object (I assume).
struct ContentView: App {
@ObservedObject var state = AppState()
var view: some View {
ItemsView(workspaces: state.workspaces!)
}
var body: some Scene {
WindowGroup {
view.environmentObject(state)
}
}
}
struct ItemsView: View {
@ObservedObject var workspaces: Results<Workspace> //<!-- Error
var body: some View {
//...
}
}
Xcode gives a syntax error on the workspaces
property:
Property type 'Results' does not match that of the 'wrappedValue' property of its wrapper type 'ObservedObject'
Is it possible to observe a set of Results
just like we can have a notification listener on a collection of Results
?
question from:
https://stackoverflow.com/questions/66055959/observe-collection-results-in-realm-with-combine-and-swiftui 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…