2 / 4
Jul 2024

Hey all,

I’m looking forward to using the .subscribe() syntax introduced in RealmSwift v 10.43.0.
However, I always get the same thread error when I try to use this syntax, although, to the best of my knowledge, I am always accessing the method from the main thread:

RealmSwift/Results.swift:189: Fatal error: `subscribe` can only be called on main thread or actor-isolated Realms

Anyone any suggestions on how to get this to work? In general, I am interested in any solution that allows me to easily add subscriptions for queries defined in @ObservedResults, instead of having to duplicate that query again in the traditional subscription syntax. Thanks in advance!

Here’s the code that leads to the error:

import SwiftUI import RealmSwift @MainActor struct ShoppingListSpecifierMenu: View { @ObservedRealmObject var user: User @ObservedRealmObject var shoppingList: ShoppingList @State var presentingNewShoppingListView = false @ObservedResults(ShoppingList.self) var shoppingListOptions @ObservedResults(ShoppingList.self) var shoppingListInivitations @Environment(\.realm) var realm init(user: User, shoppingList: ShoppingList) { _user = .init(wrappedValue: user) _shoppingList = .init(wrappedValue: shoppingList) _shoppingListOptions = .init(ShoppingList.self, where: { $0.ownerIDs.contains(user._id) }) _shoppingListInivitations = .init(ShoppingList.self, where: { $0.invitedIDs.contains(user._id) }) } var body: some View { Menu("\(shoppingList.name)") { Button { presentingNewShoppingListView.toggle() } label: { Label("new shoppinglist", systemImage: "plus.circle") } Divider() ForEach(shoppingListOptions) { shoppingListOption in Text(shoppingListOption.name) } } .sheet(isPresented: $presentingNewShoppingListView) { NewShoppingListView(user: user) } .task { try? await getSubs() } } @MainActor func getSubs() async throws { // approach one fails:// ❌ RealmSwift/Results.swift:189: Fatal error: `subscribe` can only be called on main thread or actor-isolated Realms try await self.shoppingListOptions.subscribe() // aproach two fails as well: // ❌ RealmSwift/Results.swift:189: Fatal error: `subscribe` can only be called on main thread or actor-isolated Realms // let results = try await realm.objects(ShoppingList.self) // .where { $0.invitedIDs.contains(user._id)} // .subscribe(name: "test") } }
2 months later
1 month later

Facing the same issue. I can’t get realm to be happy even thought the action is triggered from the main thread and I have the necessary @MainActor in place