Android 在不同的线程上执行工作
我执行一个领域查询 然后我需要对领域查询的结果执行一个耗时的映射,因此它需要在工作线程上完成 最后,我需要主线程上的结果(因为它们会更新UI) 但是下面的代码(可以理解)给了我一个例外:“来自错误线程的领域访问。领域对象只能在创建它们的线程上访问。”Android 在不同的线程上执行工作,android,realm,rx-java,Android,Realm,Rx Java,我执行一个领域查询 然后我需要对领域查询的结果执行一个耗时的映射,因此它需要在工作线程上完成 最后,我需要主线程上的结果(因为它们会更新UI) 但是下面的代码(可以理解)给了我一个例外:“来自错误线程的领域访问。领域对象只能在创建它们的线程上访问。” 请问我如何实现我所需要的?在领域查询之前创建一个可观察的 并使用.observeOn(AndroidScheduler.mainThread())将其放入UI线程像以前一样运行领域查询和其他操作。在领域查询之前创建一个可观察的 val defaul
请问我如何实现我所需要的?在领域查询之前创建一个可观察的
并使用
.observeOn(AndroidScheduler.mainThread())
将其放入UI线程像以前一样运行领域查询和其他操作。在领域查询之前创建一个可观察的
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)
并使用
.observeOn(AndroidScheduler.mainThread())
将其放入UI线程像以前一样运行领域查询和其他功能。您好,成功了,谢谢,请解释一下原因。您好,成功了,谢谢,请解释一下原因?
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)