Realm-java: DefaultInstance Change listener

Created on 2 Mar 2017  路  3Comments  路  Source: realm/realm-java

In my app I want to manage several realms at the same time:

1) A local management realm that only holds information about how many other database / realms are in the system

2) A main local realm.
3) A sync remote realm.

2 and 3 share the same model structure and from the app point of view are interchangable.

Except for management purpose all the application activities and fragment are using 2 or 3.
To maintain the reference count I use the setDefaultInstance, and adquire the default instance on the viewCreated and close it on the ondestroy of the activities / fragment.

However when I change the default instance, I would like the activities and fragments to automatically close the old realm and get the newer, it would be great if some kind of change listener for the setDefaultInstance method.

Is there any way to get notified when such element is changed?

T-Help

Most helpful comment

You mean, if the default realm changed? Not really? This sounds like something you would want to wrap in your own helper class?

Something like this:

public class RealmHelper {
  List<Callback> callbacks = new CopyOnWriteArrayList();
  public static setDefaultInstance(RealmConfiguration config) {
    Realm.setDefaultConfiguration(config);
    for (Callback c : callbacks) {
      c.notifyDefaultInstanceChanged();
    }
  }

  public static void registerCallback(Callback callback) {
    // ...
  }
}

All 3 comments

You mean, if the default realm changed? Not really? This sounds like something you would want to wrap in your own helper class?

Something like this:

public class RealmHelper {
  List<Callback> callbacks = new CopyOnWriteArrayList();
  public static setDefaultInstance(RealmConfiguration config) {
    Realm.setDefaultConfiguration(config);
    for (Callback c : callbacks) {
      c.notifyDefaultInstanceChanged();
    }
  }

  public static void registerCallback(Callback callback) {
    // ...
  }
}

Yes, that expecifically is what I suggested: a native support for the change of the realm default instance to avoid creating (another) wraper :). As realm is already counting the references I thought that it would be nice to be supported natively to avoid inconsistences.
But thanks for the code to manage it as a wrapper.

We have to balance the number of API's we add to Realm. In one end we want to support as many use cases as possible. In the other, it means more code to maintain and more complex API's for people to learn (and a bigger method count).

In this case, adding it to Realm itself would only support some very few specialized use cases, and since the workaround is pretty clear cut, we would rather let those few people implement it themselves.

Closing.

Was this page helpful?
0 / 5 - 0 ratings