gpt4 book ai didi

android - 执行完成后关闭 Realm 实例

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:39:16 26 4
gpt4 key购买 nike

我想在执行完成后在 executeTransactionAsync 中关闭我的 Realm 实例。原因是我的应用程序主线程一直卡住,我认为原因是后台 Realm 实例在执行完成后没有关闭。请参阅下面的代码:

realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
// Execute realm code
realm.copyToRealmOrUpdate(myData);
// Can I close the realm instance here without getting an
// error? realm.close(); causes an error.
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.i("CB", "success");
// looks like I cannot access the execute Realm
// instance here.
// Closing realm.getDefaultInstance does not change my issue
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.i("CB", "error - " + error.getMessage());
}
});
}

请看我的评论。我的应用程序屏幕变黑了。执行成功完成并调用 onSuccess(),但我无法从此处访问 execute Realm 实例以将其关闭。

关于我可以尝试什么,您有什么建议吗?我做错了什么吗?

提前谢谢你。

编辑

07-19 11:43:42.379 8146-8146/com.shortterminsurance.shortterm I/CB: success
07-19 11:43:43.258 8146-8152/com.shortterminsurance.shortterm W/art: Suspending all threads took: 33.234ms
07-19 11:43:43.266 8146-8156/com.shortterminsurance.shortterm I/art: Background partial concurrent mark sweep GC freed 476307(17MB) AllocSpace objects, 512(10MB) LOS objects, 40% free, 33MB/55MB, paused 7.261ms total 163.497ms
07-19 11:43:44.131 8146-8156/com.shortterminsurance.shortterm I/art: Background sticky concurrent mark sweep GC freed 408160(9MB) AllocSpace objects, 459(15MB) LOS objects, 35% free, 35MB/55MB, paused 10.287ms total 147.823ms
07-19 11:43:44.834 8146-8152/com.shortterminsurance.shortterm W/art: Suspending all threads took: 103.676ms
07-19 11:43:44.848 8146-8156/com.shortterminsurance.shortterm W/art: Suspending all threads took: 13.424ms

这是我的 onSuccess 被调用后的 logcat。我认为 execute 中的 realm 后台实例由于某种原因一直在运行:(。

最佳答案

此处传递的 Realm 实例

@Override
public void execute(Realm realm) {

为您关闭。您不必担心自己关闭它。

如果您查看 Realm.executeTransactionAsync() 的源代码,您可以找到

bgRealm.beginTransaction();
try {
transaction.execute(bgRealm);

if (!Thread.currentThread().isInterrupted()) {
bgRealm.commitTransaction(false, new Runnable() {
@Override
public void run() {
// The bgRealm needs to be closed before post event to caller's handler to avoid
// concurrency problem. eg.: User wants to delete Realm in the callbacks.
// This will close Realm before sending REALM_CHANGED.
bgRealm.close();
}
});
transactionCommitted = true;
}
}
...

因此,首先它会在您的事务上调用 .execute(),然后关闭它传递给您的 Realm 实例。

关于android - 执行完成后关闭 Realm 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38454402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com