Search code examples
c#xamarinrealmrealm-mobile-platform

disposing realm in xamarin


I am using Realm in Xamarin.Forms to build mobile application and have some doubts related to closing the realm in xamarin.

Following is the method to update records in realm

public  void updateData(EventType e)
        {

               Realm realm = Realm.GetInstance();
                 realm.WriteAsync(tempRealm =>
                {

                    tempRealm.Add(e.response, true);
                });

                realm.Dispose();

                MessagingCenter.Send<IMessage, EventType>(this, RestApi.UI_EVENT, e);


        }
  1. Do we need to call realm.Dispose() everytime whenever we call Realm.GetInstance(); ?
  2. Does WriteAsync takes care of closing/disposing realm ?
  3. Do i have to use await againts realm.WriteAsync as its an asynchronous method.

Solution

  • Do we need to call realm.Dispose() everytime whenever we call Realm.GetInstance?

    Yes. Eventually you should Dispose on your Realm instances when you are not longer using them. This will release any consumed resources (native and managed).

    Typically I keep a UI thread instance open during the life time of the app (following the application lifecycle for each platform). i.e. I treat this Realm instance like an HttpClient instance, an application level singleton that you can open additional instances from. Now I do open and dispose of instances on background threads when I am updating the database via services, broadcast receivers, push updates, etc...

    Note: Remember if you are on a background thread and obtain multiple Realm instances of the same RealmConfigurationBase on that thread, they actually will all be the same Realm instance (Realm.IsSameInstance). You can call Dispose on each one and not actually close (Realm.IsClosed) the instance until all the instances on that thread are disposed of.

    Does WriteAsync takes care of closing/disposing realm?

    Yes. You do not want to call Dispose on the Realm instance that is passed into your WriteAsync lamba function.

    In fact if you do you will receive a System.ObjectDisposedException since Realm has wrapped that lamba with a transaction block and you have dispose the realm instance before the transaction has been committed or rolled back.

    Do i have to use await against realm.WriteAsync as its an asynchronous method.

    Refer to the many other SOs regarding fire&forget async method calling, i.e.: Why do I have to use await for a method to run asynchronously. What if I don't want to wait for the method to finish before continuing?