Flex sync when using Mixed type: error thrown that no subscription exists yet it does

When I attempt to write a new piece of data, I get the following error:

**Terminating app due to uncaught exception 'RLMException', reason: 'Cannot write to class ctext when no flexible sync subscription has been created.'**

I am getting this error even though a subscription exists. The sub already exists, which you can verify thru the print statement output in the console log below.

This NavView is a sandbox view for me to experiment in. I included the “course” subscription and $.append call in NavView, as I separately have an actual app’s view working for course. The error does not throw on the NavView’s course subscription. The primary item this sandbox testing is experimenting with is the Mixed sync type that is used within the “ctext” class. An interesting note about the course.append… even though it does not error, the data is never added to the collection in Atlas. This is in spite of the Logs area showing a write entry:


Logs:
[
  "Upload message contains 1 changeset(s) to be integrated",
  "Integrated 1 of 1 remaining changeset(s)",
  "Integrating changesets required conflict resolution to be performed on 0 of the changesets",
  "Latest server version is now 20",
  "Number of integration attempts was 1"
]
Function Call Location:
US-OR
Query:
{
  "course": "(TRUEPREDICATE)"
}
Write Summary:
{
  "course": {
    "inserted": [
      "630ae06a65d95d89d88efefb"
    ]
  }
}
Remote IP Address:

SDK:
Realm Cocoa v10.28.4
Platform Version:
Version 15.5 (Build 19F70)

Previously, I had the subscription code set up using initialSubscriptions when the configuration is declared (higher in the view hierarchy). However, it had the same problem, and I moved it down into this sandbox view to try to isolate things better.

Reproduction code:

import Foundation
import RealmSwift
import SwiftUI

struct NavView: View {
    @ObservedResults(ctext.self) var contexts
    @ObservedResults(course.self) var courses
    @EnvironmentObject var app: RealmSwift.App
    @State var realm: Realm
    var body: some View {
        NavigationView {
            VStack {
                Button{
                    let newUnit = course()
                    newUnit.owner_id = app.currentUser?.id ?? "noid"
                    newUnit.displayName = "displayName"
                    $courses.append(newUnit)
                    
                    let c = ctext()
                    c.owner_id = app.currentUser?.id ?? "noid"
                    c.cpPath = "base"
                    $contexts.append(c)
                } label: { Text(String(contexts.count)) }
            }
        }.task {
            do {
            let subscriptions = realm.subscriptions
                if let foundSubscriptions = subscriptions.first(named: "ctext") {
                    print("ctext sub already made")
                } else {
                    print("creating ctext sub ")
                    try await subscriptions.update {
                        subscriptions.append(QuerySubscription<ctext>(name: "ctext"))
                }
                    
                    if let foundSubscriptions = subscriptions.first(named: "course") {
                        print("course sub already made")
                    } else {
                        print("creating course sub ")
                        try await subscriptions.update {
                            subscriptions.append(QuerySubscription<course>(name: "course"))}
                    }
            }
        } catch {
            print("Error info: \(error)")
        }}
    }
}

Full Console output:

2022-08-27 20:39:38.606451-0700 sample_app_dev[70377:8241788] Version 10.28.6 of Realm is now available: https://github.com/realm/realm-swift/blob/v10.28.6/CHANGELOG.md
2022-08-27 20:39:38.609030-0700 sample_app_dev[70377:8241787] Sync: Connection[1]: Session[1]: client_reset_config = false, Realm exists = true, client reset = false
2022-08-27 20:39:38.609933-0700 sample_app_dev[70377:8241787] Sync: Connection[2]: Session[2]: client_reset_config = false, Realm exists = true, client reset = false
2022-08-27 20:39:38.676231-0700 sample_app_dev[70377:8241787] Sync: Connected to endpoint '54.202.198.109:443' (from '192.168.1.11:64811')
2022-08-27 20:39:38.780715-0700 sample_app_dev[70377:8241780] [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics
ctext sub already made
2022-08-27 20:39:41.509175-0700 sample_app_dev[70377:8241587] *** Terminating app due to uncaught exception 'RLMException', reason: 'Cannot write to class ctext when no flexible sync subscription has been created.'
*** First throw call stack:
(
	0   CoreFoundation                      0x000000010b407604 __exceptionPreprocess + 242
	1   libobjc.A.dylib                     0x0000000108f61a45 objc_exception_throw + 48
	2   sample_app_dev                      0x0000000104d5639a _ZN18RLMAccessorContext12createObjectEP11objc_objectN5realm12CreatePolicyEbNS2_6ObjKeyE + 3114
	3   sample_app_dev                      0x0000000104e61fb8 RLMAddObjectToRealm + 280
	4   sample_app_dev                      0x000000010515fca5 $s10RealmSwift0A0V3add_6updateySo0aB6ObjectC_AC12UpdatePolicyOtF + 1077
	5   sample_app_dev                      0x000000010519132e $s10RealmSwift15BoundCollectionPAASo0aB6ObjectC7ElementRczAA7ResultsVyAGG5ValueRtzrlE6appendyyAGFyAJXEfU_ + 286
	6   sample_app_dev                      0x000000010517e8f9 $s10RealmSwift9safeWrite33_06F2B43D1E2DA64D3C5AC1DADA9F5BA7LLyyx_yxXEtAA14ThreadConfinedRzlFyyXEfU_ + 57
	7   sample_app_dev                      0x000000010517e91f $ss5Error_pIgzo_ytsAA_pIegrzo_TR + 15
	8   sample_app_dev                      0x00000001051b37f4 $ss5Error_pIgzo_ytsAA_pIegrzo_TRTA + 20
	9   sample_app_dev                      0x000000010515e833 $s10RealmSwift0A0V5write16withoutNotifying_xSaySo20RLMNotificationTokenCG_xyKXEtKlF + 275
	10  sample_app_dev                      0x000000010517e798 $s10RealmSwift9safeWrite33_06F2B43D1E2DA64D3C5AC1DADA9F5BA7LLyyx_yxXEtAA14ThreadConfinedRzlF + 1080
	11  sample_app_dev                      0x00000001051911db $s10RealmSwift15BoundCollectionPAASo0aB6ObjectC7ElementRczAA7ResultsVyAGG5ValueRtzrlE6appendyyAGF + 1419
	12  sample_app_dev                      0x0000000104d1424e $s14sample_app_dev7NavViewV4bodyQrvg7SwiftUI6VStackVyAE6ButtonVyAE4TextVGGyXEfU_ALyXEfU_yycfU_ + 1406
	13  SwiftUI                             0x00000001156b3841 $s7SwiftUI18WrappedButtonStyle33_AEEDD090E917AC57C12008D974DC6805LLV8makeBody13configurationQrAA09PrimitivedE13ConfigurationV_tFyycAHcfu_yycfu0_TA + 17
	14  SwiftUI                             0x0000000115bd6163 $s7SwiftUI25PressableGestureCallbacksV8dispatch5phase5stateyycSgAA0D5PhaseOyxG_SbztFyycfU_ + 32
	15  SwiftUI                             0x00000001157cca1e $sIeg_ytIegr_TR + 12
	16  SwiftUI                             0x000000011549653a $sIeg_ytIegr_TRTA + 17
	17  SwiftUI                             0x00000001154e15bc $sIeg_ytIegr_TRTA.5406 + 9
	18  SwiftUI                             0x00000001157cca32 $sytIegr_Ieg_TR + 12
	19  SwiftUI                             0x00000001157cca1e $sIeg_ytIegr_TR + 12
	20  SwiftUI                             0x000000011549653a $sIeg_ytIegr_TRTA + 17
	21  SwiftUI                             0x00000001154e15c7 $sIeg_ytIegr_TRTA.5414 + 9
	22  SwiftUI                             0x00000001157a633e $s7SwiftUI6UpdateO3endyyFZ + 410
	23  SwiftUI                             0x00000001158a1a11 $s7SwiftUI19EventBindingManagerC4sendyySDyAA0C2IDVAA0C4Type_pGF + 280
	24  SwiftUI                             0x0000000115dbf209 $s7SwiftUI18EventBindingBridgeC4send_6sourceySDyAA0C2IDVAA0C4Type_pG_AA0cD6Source_ptFTf4nen_nAA22UIKitGestureRecognizerC_Tg5 + 1825
	25  SwiftUI                             0x0000000115dbd766 $s7SwiftUI22UIKitGestureRecognizerC4send025_062C14327F4C9197D92807A7H6DF7F3BLL7touches5event5phaseyShySo7UITouchCG_So7UIEventCAA10EventPhaseOtF + 66
	26  SwiftUI                             0x0000000115dbdf0a $s7SwiftUI22UIKitGestureRecognizerC12touchesBegan_4withyShySo7UITouchCG_So7UIEventCtFToTm + 138
	27  SwiftUI                             0x0000000115dbd7ee $s7SwiftUI22UIKitGestureRecognizerC12touchesEnded_4withyShySo7UITouchCG_So7UIEventCtFTo + 40
	28  UIKitCore                           0x000000012d3988b5 -[UIGestureRecognizer _componentsEnded:withEvent:] + 217
	29  UIKitCore                           0x000000012d96337f -[UITouchesEvent _sendEventToGestureRecognizer:] + 662
	30  UIKitCore                           0x000000012d38cd6b __47-[UIGestureEnvironment _updateForEvent:window:]_block_invoke + 70
	31  UIKitCore                           0x000000012d38c9f5 -[UIGestureEnvironment _updateForEvent:window:] + 516
	32  UIKitCore                           0x000000012d90fe24 -[UIWindow sendEvent:] + 5290
	33  UIKitCore                           0x000000012d8e5eac -[UIApplication sendEvent:] + 820
	34  UIKitCore                           0x000000012d97df0a __dispatchPreprocessedEventFromEventQueue + 5614
	35  UIKitCore                           0x000000012d98135d __processEventQueue + 8635
	36  UIKitCore                           0x000000012d977af5 __eventFetcherSourceCallback + 232
	37  CoreFoundation                      0x000000010b3744a7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
	38  CoreFoundation                      0x000000010b37439f __CFRunLoopDoSource0 + 180
	39  CoreFoundation                      0x000000010b37386c __CFRunLoopDoSources0 + 242
	40  CoreFoundation                      0x000000010b36df68 __CFRunLoopRun + 871
	41  CoreFoundation                      0x000000010b36d704 CFRunLoopRunSpecific + 562
	42  GraphicsServices                    0x000000010a5d9c8e GSEventRunModal + 139
	43  UIKitCore                           0x000000012d8c665a -[UIApplication _run] + 928
	44  UIKitCore                           0x000000012d8cb2b5 UIApplicationMain + 101
	45  SwiftUI                             0x0000000115d90e5d $s7SwiftUI17KitRendererCommon33_ACC2C5639A7D76F611E170E831FCA491LLys5NeverOyXlXpFAESpySpys4Int8VGSgGXEfU_ + 196
	46  SwiftUI                             0x0000000115d90d97 $s7SwiftUI6runAppys5NeverOxAA0D0RzlF + 148
	47  SwiftUI                             0x0000000115753854 $s7SwiftUI3AppPAAE4mainyyFZ + 61
	48  sample_app_dev                      0x0000000104d451de $s14sample_app_dev15realmSwiftUIAppV5$mainyyFZ + 30
	49  sample_app_dev                      0x0000000104d45269 main + 9
	50  dyld                                0x0000000108bd0f21 start_sim + 10
	51  ???                                 0x000000011526751e 0x0 + 4649809182
)
libc++abi: terminating with uncaught exception of type NSException
dyld4 config: DYLD_ROOT_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot DYLD_LIBRARY_PATH=/Users/josephbittman/Library/Developer/Xcode/DerivedData/sample_app-dtakijxdnijtkegdverncnbkrzqg/Build/Products/Debug-iphonesimulator:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/system/introspection DYLD_INSERT_LIBRARIES=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libBacktraceRecording.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/usr/lib/libMainThreadChecker.dylib:/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS.simruntime/Contents/Resources/RuntimeRoot/Developer/Library/PrivateFrameworks/DTDDISupport.framework/libViewDebuggerSupport.dylib DYLD_FRAMEWORK_PATH=/Users/josephbittman/Library/Developer/Xcode/DerivedData/sample_app-dtakijxdnijtkegdverncnbkrzqg/Build/Products/Debug-iphonesimulator:/Users/josephbittman/Library/Developer/Xcode/DerivedData/sample_app-dtakijxdnijtkegdverncnbkrzqg/Build/Products/Debug-iphonesimulator/PackageFrameworks
*** Terminating app due to uncaught exception 'RLMException', reason: 'Cannot write to class ctext when no flexible sync subscription has been created.'
terminating with uncaught exception of type NSException
CoreSimulator 802.6.1 - Device: iPhone 11 Pro (99012B61-5D78-46FB-A87D-B3FA37C14553) - Runtime: iOS 15.5 (19F70) - DeviceType: iPhone 11 Pro
(lldb)

So, it turned out that Sync needed to be terminated and restarted.

Maybe the subscriptions object allowed creating a subscription to the offline data and not server and so it appeared a subscription was made? But then I would think it would have allowed me to .append to the offline data even tho the server connectivity was not there… and I can manually recover the changes when it goes back online for a client reset.

And I don’t know why the Logs for the course .append showed (or seemed to me) success even though it didn’t?

Few things to improve there if there is dev bandwidth… Not the first time I’ve spent a half day on something to realize it was fixed after restarting sync. I’ve learned to check Sync since this has occurred a few times, but when I’m experimenting with new features, I just don’t recall to do so.

I had another occurance of this same error being thrown. This time, I terminated sync and started again. Same error. Terminated sync a second time and started; no error.

@Joseph_Bittman Can you please share the code how you inject the realm to the environment values.
Something like this,
.environment(\.realmConfiguration, user!.flexibleSyncConfiguration())
this is actually very important because this configuration is the one been used by the @ObservedResults

I would also suggest to use
@Environment(\.realm) var realm if you are doing the subscription on the same view.

in app main:

**let** realmApp = App(id: theAppConfig.appId, configuration: AppConfiguration(baseURL: theAppConfig.baseUrl, transport: **nil** , localAppName: **nil** , localAppVersion: **nil** ))

            ContentView().environmentObject(realmApp)

in content view: (based off of realm template)

let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
                  if let foundSubscriptions = subs.first(named: "course") {
                      return
                  } else {

                      subs.append(QuerySubscription<course>(name: "course"))
                      subs.append(QuerySubscription<ctext>(name: "ctext"))
.......                      
                  }
              })
.......

            OpenRealmView().environment(\.realmConfiguration, config)

in openrealmview:

    @AsyncOpen(appId: theAppConfig.appId, timeout: 4000) var asyncOpen
.........
           [viewname](realm: realm).environment(\.realm, realm)

Hi @Joseph_Bittman , you have to make sure that the realm used by the ObservedResults which you are using to append new objects is the same realm that you added the subscriptions. Which version of realm are you using?
I tested the following code, which seems similar to yours and seems to be working fine
Realm version 10.28.6

class Contact: Object, ObjectKeyIdentifiable {
    @Persisted(primaryKey: true) var _id: String = UUID().uuidString
    @Persisted var name: String = ""
    @Persisted var lastName: String = ""
    @Persisted var email: String = ""
    @Persisted var birthdate: Date = Date()
}

// For the purpose of this example, we have to ways of syncing, using @AsyncOpen and @AutoOpen
struct ContentView: View {
    var body: some View {
        NavigationView {
            LoginView()
        }
    }
}

// LoginView, Authenticate User
// When you have enabled anonymous authentication in the Realm UI, users can immediately log into your app without providing any identifying information:
// Documentation of how to login can be found (https://docs.mongodb.com/realm/sdk/ios/quick-start-with-sync/)
struct LoginView: View {
    @ObservedObject var loginHelper = LoginHelper()
    @State var isLogged = false

    var body: some View {
        VStack {
            if isLogged {
                if let user = loginHelper.user {
                    let configuration = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
                        subs.append(QuerySubscription<Contact>(name: "contacts"))
                    })
                    AsyncOpenView()
                        .environment(\.realmConfiguration, configuration)
                } else {
                    EmptyView()
                }
            } else {
                Button("Login") {
                    loginHelper.login() {
                        isLogged = true
                    }
                }
            }
        }
        .padding()
        .navigationTitle("Logging View")
    }
}

class LoginHelper: ObservableObject {
    var cancellables = Set<AnyCancellable>()
    var user: User?

    func login(completion: @escaping () -> Void) {
        let app = RealmSwift.App(id: appId)
        app.login(credentials: .anonymous)
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { results in

            }, receiveValue: { user in
                self.user = user
                completion()
            })
            .store(in: &cancellables)
    }
}

struct AsyncOpenView: View {
    @AsyncOpen(appId: appId, timeout: 4000) var asyncOpen

    var body: some View {
        VStack {
            switch asyncOpen {
            case .connecting, .waitingForUser, .progress:
                ProgressView()
            case .error:
                EmptyView()
            case .open(let realm):
                ListView()
                    .environment(\.realmConfiguration, realm.configuration)
            }
        }
    }
}

struct ListView: View {
    @ObservedResults(Contact.self) var contacts
    @Environment(\.realm) var realm
    @State var searchString: String = ""

    var body: some View {
        VStack {
            SwiftUI.List {
                ForEach(contacts) { contact in
                    HStack {
                        Text(contact.name)
                    }
                }
            }
        }
        .navigationBarItems(trailing: HStack {
            Button("add") {
                let contact = Contact()
                contact.name = "name_\(Int.random(in: 0...100))"
                $contacts.append(contact)
            }
        })
    }
}

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.