2017-10-29 5 views
0

나는 영역 쿼리를 실행하는 작업을 수행, 그 결과는 작업자 스레드에서 수행해야합니다.<p></p> 다음 나는 영역 쿼리의 결과 매핑을 소비하는 시간을 수행해야, 다른 스레드

마지막으로 주 스레드에서 결과가 필요합니다 (UI를 업데이트하기 때문에).

그러나 다음 코드 (당연히)는 나에게 예외를 제공합니다. "잘못된 스레드에서 영역 액세스. 영역 객체는 작성된 스레드에서만 액세스 할 수 있습니다."

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) 

내가 원하는 것을 어떻게 달성 할 수 있습니까?

답변

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) 
+0

안녕하세요, 그 트릭을, 고마워요, 왜 설명 할 수 있니? –

1

영역 쿼리 전에 Observable을 만들고 .observeOn(AndroidScheduler.mainThread())으로 UI 스레드에 넣으십시오.
이전처럼 Realm 쿼리와 다른 것들을 실행하십시오.