gpt4 book ai didi

android - Realm 无法在新线程中执行 executeTransaction

转载 作者:行者123 更新时间:2023-11-30 05:04:56 24 4
gpt4 key购买 nike

上面代码中,realm不能在新的Thread中执行它的事务,没有报错,但是也没有执行。

我已经尝试将事务放在线程之外,问题是它消耗了 UI 线程,但它工作得很好,我想在 Retrofit 和 Realm 工作时向用户显示平滑加载

threadNova = new Thread() {
@Override
public void run() {
super.run();

try {
Response<Retorno> response = getCall.execute();
final Retorno responsebody = response.body();
Realm realm = Realm.getDefaultInstance();

realm.executeTransaction(realm1 -> {
//Save things on bank
// No errors but don't enter here either
});
} catch (IOException e) {
e.printStackTrace();
}
}
};

最佳答案

您需要调用 Realm.close()

您使用没有循环器的 Java 线程,这意味着您的 Realm 在您调用 Realm.close() 之前不会刷新,因此请在 finally block 中关闭您的 Realm。

    try(Realm realm = Realm.getDefaultInstance()) {
Response<Retorno> response = getCall.execute();
final Retorno responsebody = response.body();

realm.executeTransaction(realm1 -> {
//Save
});

} catch (IOException e) {
e.printStackTrace();
}
}

来自文档:

If you obtain a Realm instance from a thread associated with a Looper, the Realm instance comes with an auto-refresh feature. (Android’s UI thread is a Looper.) This means the Realm instance will be periodically updated to the latest version. This lets you keep your UI constantly updated with the latest content with almost no effort!

If you get a Realm instance from a thread that does not have a Looper attached, objects from that instance won’t be updated until you call the waitForChange method. Holding on to an old version of your data is expensive in terms of memory and disk space, and the cost increases with the number of versions between the one being retained and the latest. This is why it is important to close the Realm instance as soon as you are done with it in the thread.

If you want to check whether your Realm instance has auto-refresh activated or not, use the isAutoRefresh method. soon as you are done with it in the thread.

关于android - Realm 无法在新线程中执行 executeTransaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736819/

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