Offline - Launch Unity with MongoDB Realm

I’m building a game in unity and the players’ data are stored in a MongoDB Realm DB with Sync enabled. When I launch the game online, it works fine and if I close and re-open, the user is still here.

My problem occurs when I close, set offline mode on my device, and get back: it’s not finding any users. Is it just not a Realm Sync feature? Hope you’ve got some answers :wink:

realmApp = App.Create(new AppConfiguration(AppId)
{
    MetadataPersistenceMode = MetadataPersistenceMode.NotEncrypted
});

if (realmApp.CurrentUser == null)
{
    SceneManager.LoadScene("user_login");
}
else
{
    // Does not work offline
    realmUser = realmApp.CurrentUser;
    realmInstance = await Realm.GetInstanceAsync(new PartitionSyncConfiguration(realmUser.Id, realmUser));
    SceneManager.LoadScene("project_list");
}```

Hey, yeah, GetInstanceAsync will attempt to contact the server and download the latest data. You can either supply a cancellation token to timeout the wait after e.g. 10 seconds or use GetInstance instead:

// option 1
var config = new PartitionSyncConfiguration(realmUser.Id, realmUser);
try
{
    var cts = new CancellationTokenSource(10_000); // cancel after 10s
    realmInstance = await Realm.GetInstanceAsync(config, cts.Token);
}
catch (TaskCancelledException)
{
    // GetInstanceAsync timed out, let's fall back to using the local data
    realmInstance = Realm.GetInstance(config);
}

// Option 2
realmInstance = await Realm.GetInstanceAsync(new PartitionSyncConfiguration(realmUser.Id, realmUser));

Our general recommendation would be to use option 2 as that reduces the wait time for your end users and they can jump in the game straight away. However, if it’s critical that you attempt to load the latest data on every launch, then you can go with option 1.

1 Like

Its working perfectly fine, the user gets his data offline in local and when it goes online, everythings connect properly. Thanks a lot !

To understand better, its working because you added the cts.Token ? because if offline you put GetInstance instead of GetInstanceAsync ?

Thanks again !!

The difference between GetInstance and GetInstanceAsync is that the latter will try to connect to the server and ensure that all remote data has been downloaded before returning. All Realm data is stored locally on the device and synchronized with the server in the background. So using GetInstance after a user has already logged in tells the app to just use whatever data it already has available and Realm will try to contact the server in the background and pull new data as it becomes available.

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