swiftasync-awaitrealm

Realm accessed from incorrect thread using async and await


Running the code below i get "Realm accessed from incorrect thread." error on the second try! realm.write({ line , the first write line causes no error. Any idea on how to fix it?

let realm = try! await Realm()
                        print("User Realm User file location: \(realm.configuration.fileURL!.path)")
                        try! realm.write { // <= No error here
                            realm.add(groups, update: .modified)
                        }
                        StartApp._Groups = groups
                        if let items  = await api.getArticles(aricleIDs: ids) {
                            try! realm.write({ // <= Error here
                                realm.add(items, update: .modified)
                            })
                            StartApp._Items = items
                            var index = 0
                            StartApp._Items = StartApp.Items.map { item in
                                item.i = index
                                index = index + 1
                                return item
                            }
                            groups.forEach { group in
                                group.items = items.filter({ $0.groupId == group.id })
                            }
                        }

Solution

  • i fixed with the below , removed the await Realm() and consolidated writes into one

    DispatchQueue.main.async{
                            do {
                                let realm = try Realm()
               
                                var index = 0
                                items.forEach { item in
                                    item.i = index
                                    index = index + 1
                                }
                                try realm.write({
                                    realm.add(groups, update: .modified)
                                    realm.add(items, update: .modified)
                                   }
                                })
                            } catch {
                                print("Realm error: \(error)")
                            }
                        }