アプリケーションのライフサイクル全体を通して1つのレルムインスタンスを維持し、それを閉じる方法を教えてください。アプリのライフサイクル全体で1つのRealmインスタンスを維持する方法とそれを閉じますか?
シングルトンクラスを使用してインスタンスをメンテナンスすることはできますが、アプリケーションを終了したらどうすれば閉じることができますか?
また、一度開いたレルムインスタンスを閉じないと安全ですか?
アプリケーションのライフサイクル全体を通して1つのレルムインスタンスを維持し、それを閉じる方法を教えてください。アプリのライフサイクル全体で1つのRealmインスタンスを維持する方法とそれを閉じますか?
シングルトンクラスを使用してインスタンスをメンテナンスすることはできますが、アプリケーションを終了したらどうすれば閉じることができますか?
また、一度開いたレルムインスタンスを閉じないと安全ですか?
レルムインスタンスのラッピングクラス(シングルトンの可能性があります)を作成してからいくつかのメソッドを追加すると、レルムを閉じるのではなく、独自のメソッドを呼び出して終了したらすぐにインスタンスを使用しましたか?このようなもの。
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();
}
}
私は、UIスレッドのため、と私は/ try-with-sources
ブロックを使用してレルムを閉じる開くバックグラウンドスレッドのためにシングルトンRealmManager
を使用する傾向があります。
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;
}
}
}
とバックグラウンドスレッドの:UIスレッドのだから、
try(Realm realm = Realm.getDefaultInstance()) {
// ...
}
が開閉レルムを何度も何度もありませんが、より多くのメモリを消費しますか?多分パフォーマンスのヒット –
完了したらインスタンスを閉じることをお勧めします。この場合、私は彼がやっているのはオブジェクトを保存することだと仮定したので、領域は閉じなければなりません。 –
これは保存時に機能しますが、クエリでは機能しません。 – EpicPandaForce