好的,所以这并不能真正解决问题(但它至少会尝试在主线程上关闭领域),但可以让您调试打开未关闭领域的原因和位置。
只需获取一个实例TraceableRealm.getInstance(realmConfig, "I needed it for that tiny query")
并关闭TraceableRealm
实例,而不仅仅是Realm
.
在里面realmIndex
你会得到一个仍然 openRealm
的列表以及线程和它们存在的原因......
class TraceableRealm(
val realm: Realm,
val thread: String,
val purpose: String
): Closeable
{
companion object {
val realmIndex = mutableListOf<TraceableRealm>()
fun getInstance(config: RealmConfiguration, purpose: String): TraceableRealm {
val newRealm = TraceableRealm(Realm.getInstance(config), Thread.currentThread().name, purpose)
realmIndex.add(newRealm)
realmIndex.removeAll { !it.isOpen }
return newRealm
}
fun killZombies() {
runUI {
realmIndex.filter { it.isOpen && it.thread == Thread.currentThread().name }.forEach {
try {
it.close()
} catch (ex: Exception) {
Timber.d("Problem removing zombie realm: $it")
}
}
realmIndex.removeAll { !it.isOpen }
realmIndex.forEach {
Timber.d("Couldn't close realm: $it")
}
}
}
}
var isOpen = true
override fun toString(): String {
return "$purpose in $thread open=$isOpen"
}
override fun close() {
realm.close()
isOpen = false
}
}