Search code examples
realmswiftui

How to use Realm with SwiftUI


I have been trying to figure out how to use Realm with SwiftUI. The problem is that SwiftUI and Realm both have a List type. When you import SwiftUI into your Realm model to make the class a BindableObject and try to create a Realm List property there is an error.

Is it possible to use an instance of the Realm object model and make it a BindableObject in SwiftUI?


Solution

  • Sure, it's very simple, use the module identifier as prefix like this :

    let members = RealmSwift.List<Member>()
    

    Now to the second part of your question. It's easy to encapsulate a Realm object (or list, or resultset) in an BindableObject :

    final class DBData: BindableObject  {
    
        let didChange = PassthroughSubject<DBData, Never>()
    
        private var notificationTokens: [NotificationToken] = []    
        var posts = Post.all
    
        init() {
            // Observe changes in the underlying model
            self.notificationTokens.append(posts.observe { _ in
                self.didChange.send(self)
            })
    
            self.notificationTokens.append(Message.all.observe { _ in
                self.didChange.send(self)
            })
        }
    }
    

    If you "link" a DBData instance to a SwiftUI View by either using @ObjectBinding or @EnvironmentObject the UI will be refreshed and the new value for posts (in our example here) will be available each time the underlying realm changes.