PSA: Realm.NET does not keep objects alive even when event handlers are registered

So not quite going as far as calling this a bug, but it caused us huge headaches.

We’re migrating a legacy Realm Cloud app over to MongoDB Realm/Realm Sync, and the app makes heavy use of Reactive Extensions and DynamicData for reactive streams processing. It all worked fine on Realm Cloud, but we found that infuriatingly non-deterministically, various complex reactive pipelines would just stop firing after running the app for a while on MongoDB Realm, although we’d not touched that part of the code.

We eventually figured out that it appears MongoDB Realm does not keep strong references to objects/collections retrieved from it, even if one registers event handlers on those objects to get change notifications (say, as a source of observable events in a reactive pipeline that ultimately feeds the UI).

This means if you do something like this in code:

    var company = _realm.Find<Company>("companyId");

    company.Employees.SubscribeForNotifications((_, _, _) =>
          Console.WriteLine($"Employee collection changed!"));

You can expect that it’ll probably work for a little while, but unless your app directly or indirectly keeps a reference to that specific Employees collection instance (since every fetch from Realm returns a new instance), sooner or later it’ll get GC’d and your event notifications will magically stop even though the collection of employees is still being updated in Realm.

This is a breaking change from legacy Realm Cloud client behaviour, and also in my experience violates the principle of least-surprise. So to Realm.Net devs, is this intentional? Either way, please consider changing it! We really did lose a lot of time and effort figuring out what was going on here.

Hopefully it might save someone else from the grey hairs it gave us.

Hey, thanks for the report and apologies for the gray hairs :confused: This code hasn’t changed in ages, so I’m surprised it used to behave differently with the legacy cloud. That being said, I agree it’s surprising and probably a bug. We’ll need to think more about it to make sure we don’t introduce memory leaks - I filed Notification tokens don't keep collections alive · Issue #2837 · realm/realm-dotnet · GitHub to track it.

1 Like