如何在应用程序的整个生命周期内维护单个Realm实例并关闭它。
我可以使用单例类来维护实例,但是当关闭应用程序时如何关闭它呢?
此外,打开后不关闭Realm Instance是否安全?
答案 0 :(得分:3)
我倾向于使用单个RealmManager
作为UI线程,对于后台线程,我使用try-with-sources
块打开/关闭Realm。
对于UI线程:
public class RealmManager {
private static final String TAG = "RealmManager";
static Realm realm;
static RealmConfiguration realmConfiguration;
public static void initializeRealmConfig(Context appContext) {
if(realmConfiguration == null) {
Log.d(TAG, "Initializing Realm configuration.");
setRealmConfiguration(new RealmConfiguration.Builder(appContext).initialData(new RealmInitialData())
.deleteRealmIfMigrationNeeded()
.inMemory()
.build());
}
}
public static void setRealmConfiguration(RealmConfiguration realmConfiguration) {
RealmManager.realmConfiguration = realmConfiguration;
Realm.setDefaultConfiguration(realmConfiguration);
}
private static int activityCount = 0;
public static Realm getRealm() {
return realm;
}
public static void incrementCount() {
if(activityCount == 0) {
if(realm != null) {
if(!realm.isClosed()) {
Log.w(TAG, "Unexpected open Realm found.");
realm.close();
}
}
Log.d(TAG, "Incrementing Activity Count [0]: opening Realm.");
realm = Realm.getDefaultInstance();
}
activityCount++;
Log.d(TAG, "Increment: Count [" + activityCount + "]");
}
public static void decrementCount() {
activityCount--;
Log.d(TAG, "Decrement: Count [" + activityCount + "]");
if(activityCount <= 0) {
Log.d(TAG, "Decrementing Activity Count: closing Realm.");
activityCount = 0;
realm.close();
if(Realm.compactRealm(realmConfiguration)) {
Log.d(TAG, "Realm compacted successfully.");
}
realm = null;
}
}
}
对于后台线程:
try(Realm realm = Realm.getDefaultInstance()) {
// ...
}
答案 1 :(得分:0)
为什么不为你的领域实例创建一个包装类(可能是一个单例)然后添加一些方法,这样每次你只需调用自己的方法关闭就可以关闭领域你完成后立即使用的实例?这样的事情。
public class WrappingRealm {
public static WrappingRealm getInstance() {
//create your singleton here. Be aware of synchronization issues
}
private Realm getRealm() {
return Realm.getDefaultInstance();
}
public void save(RealmModel obj) {
Realm currentRealm = getRealm();
currentRealm.executeTransaction {
//Do your stuff
}
currentRealm.close();
}
}