NotifyMe – Realm

This is second step of adding history feature to my application. First part is here.
I have well prepared views so it is time to write service for database.

Every model which you want to store in Realm database should inherit from RealmObject class. Here is mine:

    public class SentMessage : RealmObject
    {
        public SentMessage()
        {
        }

        public SentMessage(string receiver, string body, string date)
        {
            Receiver = receiver;
            Body = body;
            Date = date;
        }

        public string Body { get; set; }

        public string Receiver { get; set; }

        public string Date { get; set; }
    }

Important thing this is that model must have public parameterless constructor.
Next step was to create a simple interface.

    public interface IDatabaseService
    {
        IEnumerable<T> GetAll<T>() where T : RealmObject;

        void Add<T>(T obj) where T : RealmObject;
    }

with following implementation:

    public class DatabaseService : IDatabaseService
    {
        public void Add<T>(T obj) where T : RealmObject
        {
            var db = Realm.GetInstance();
            db.Write(() =>
            {
                db.Add<T>(obj);
            });
        }

        public IEnumerable<T> GetAll<T>() where T : RealmObject
        {
            var db = Realm.GetInstance();
            return db.All<T>().ToList();
        }
    }

The second important thing is that every action of addition must be executed within a transaction opened by Write method.

I also registered newly created interface with implementation in my IoC container.
Thanks to that I can use it in logic responsible for sending messages.

DatabaseService.Add<SentMessage>(new SentMessage(Cache.SelectedFriend.Name, MessageBody, DateTime.Now.ToString()));

I want to refresh HistoryViewModel after every sent message. To achieve that I used a mediator pattern provided by Messanger from MVVM light library.
With the following method I registered HistoryViewModel object to receive specific messages.

Messenger.Default.Register<RefreshHistoryMessage>(this, RefreshHistoryHandler);

where RefreshHistoryHandler is a method where I put my logic. This method is called when RefreshHistoryMessage is sent with following method:

Messenger.Default.Send<RefreshHistoryMessage>(new RefreshHistoryMessage());

Basic history feature is done.
In next, last step I am going to add an ability to delete specific message from history and to clear it completely.

As you can see Realm is really easy to use, community recommended, cross-platform database. Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *