我执行Realm查询,
然后我需要执行Realm查询结果的耗时映射,因此需要在工作线程上完成。
最后我需要主线程上的结果(因为它们更新了UI)。
但是下面的代码(可以理解)给了我一个例外:" Realm从错误的线程访问。 Realm对象只能在创建它们的线程上访问。"
val defaultInstance = Realm.getDefaultInstance()
val subscription = defaultInstance
.where(Bar::class.java)
.equalTo("foo", true)
.findAllAsync()
.asObservable()
.filter { it.isLoaded && it.isValid }
.map { defaultInstance.copyFromRealm(it) }
// The following is a time consuming task, I need to perform it on another thread
.observeOn(workerScheduler)
.map { someComplexMapping(it) }
// but the results are needed on the main thread (because it updates the UI)
.subscribeOn(mainThreadScheduler)
.subscribe(observer)
请问我如何实现我的目标?
答案 0 :(得分:2)
val defaultInstance = Realm.getDefaultInstance()
val subscription = defaultInstance
.where(Bar::class.java)
.equalTo("foo", true)
.findAllAsync()
.asObservable()
.subscribeOn(mainThreadScheduler)
.filter { it.isLoaded && it.isValid }
.observeOn(Schedulers.io())
.map {
Realm.getDefaultInstance().use {
//it.refresh() // shouldn't be needed
it.copyFromRealm(it.where(Bar::class.java).equalTo("foo", true).findAll())
}
}
// The following is a time consuming task, I need to perform it on another thread
.observeOn(workerScheduler)
.map { someComplexMapping(it) }
// but the results are needed on the main thread (because it updates the UI)
.observeOn(mainThreadScheduler)
.subscribe(observer)
答案 1 :(得分:1)
在Realm查询之前创建Observable
并使用.observeOn(AndroidScheduler.mainThread())
将其放入UI线程中。
运行Realm查询以及之前的其他内容。