简体   繁体   中英

Realm with live data and RxJava in Kotlin

I am trying to use Realm in a Kotlin based application.

I set up a basic project, which tested adding elements into realm, and observing them with live data and a view model.

Then I wanted to add in some other observables, and use combineLatest of RxJava to combine them.

I created Rx Observables for all observables. I observe the live data from Realm, and then call RxJava BehaviourSubject's onNext() method to set one of the Rx Observables to be the same value as the observed realm data. This works fine, but as soon as I added in a Throttle to the Rx Operators, I got the following error message:

Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created. at io.realm.BaseRealm.checkIfValid(BaseRealm.java:442) at io.realm.com_example_myapplication_ItemRealmProxy.realmGet$id(com_example_myapplication_ItemRealmProxy.java:105) at io.realm.com_example_myapplication_ItemRealmProxy.toString(com_example_myapplication_ItemRealmProxy.java:661)

This is parts of my code:

 private val itemViewModel: ItemViewModel by lazy {
        ViewModelProviders.of(this).get(ItemViewModel::class.java)
    }

    val itemsSubject = BehaviorSubject.createDefault(listOf<Item>())
    val intsSubject = BehaviorSubject.createDefault(4)



itemViewModel.getItemData().observe(this, Observer<RealmResults<Item>> { t ->
            val items = t.map {
                it
            }

            itemsSubject.onNext(items)
        })

  Observables.combineLatest(itemsSubject, intsSubject) { a, b ->
        a
    }.throttleLast(500, TimeUnit.MILLISECONDS).subscribe {
        Log.i("Items", "Items combined read: ${it}")
    }

I can't see how realm is coupled to the onNext call, nor the throttle. Seems very weird.

Ideally I would like to stick to just Live data, but I need to do operations with other observables, and RxJava is good for this.

I needed to observe the RxJava on the main thread, as follows:

 Observables.combineLatest(itemsSubject, intsSubject) { a, b ->
            a
        }.throttleLast(500, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            Log.i("Items", "Items combined read: ${it}")
        }
    }

In a sense, the Realm error was misleading, because it was ultimately an incorrect use of RxJava.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM