我想将领域结果映射到不可变的视图模型,并且我想听结果更改,因此我将它们发送给PublishSubject,但是,直到旋转设备,数据才出现在我的recyclerview中,当我删除observeOn(AndroidSchedulers.mainThread())
时,此问题已解决。
存储库:
fun notionsChanges(state: Boolean): Observable<Pair<MutableList<Notion>, OrderedCollectionChangeSet?>> {
val notionsChanges = PublishSubject.create<Pair<MutableList<Notion>, OrderedCollectionChangeSet?>>()
val realm = Realm.getDefaultInstance()
val queryResult = realm.where<Notion>()
.equalTo("isArchived", state)
.findAllAsync()
val listener: OrderedRealmCollectionChangeListener<RealmResults<Notion>> = OrderedRealmCollectionChangeListener { realmResults, changeSet ->
if (realmResults.isValid && realmResults.isLoaded) {
val results: MutableList<Notion> = realm.copyFromRealm(realmResults)
notionsChanges.onNext(results to changeSet)
}
}
queryResult.addChangeListener(listener)
notionsChanges.doFinally {
queryResult.removeChangeListener(listener)
closeRealm(realm)
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
return notionsChanges
}
在演示者中,我使用此可观察对象将模型映射到视图模型,然后在(在订阅时)在recyclerview中的片段中显示数据:
private var subscriptions: CompositeDisposable = CompositeDisposable()
override fun onResume() {
super.onResume()
showData()
}
override fun onPause() {
subscriptions.clear()
super.onPause()
}
private fun showData() {
val viewModel = present(idleStates, resources, isIdle)
with(viewModel) {
subscriptions.addAll(
notionsChanges.subscribe(notionsAdapter::handleChanges),
//other subscriptions.
)
}
}
notionsAdapter.handleChanges:
fun handleChanges(collectionChange: Pair<List<NotionCompactViewModel>, OrderedCollectionChangeSet?>) {
val (collection, changeset) = collectionChange
debug("${collection.size}") //correctly prints the actual size of the collection.
replaceAll(collection)
if (changeset == null)
notifyDataSetChanged()
else {
for (change in changeset.changeRanges)
notifyItemRangeChanged(change.startIndex, change.length)
for (insertion in changeset.insertionRanges)
notifyItemRangeInserted(insertion.startIndex, insertion.length)
for (deletion in changeset.deletionRanges)
notifyItemRangeRemoved(deletion.startIndex, deletion.length)
}
}
对不起,如果代码不清楚。
edit :我的onBindViewHolder
有时不会被调用(当然,当recyclerview为空时)。
答案 0 :(得分:0)
从Realm 5.0开始,不再使用changeset == null
发出初始变更集。
您需要检查:
if(changeSet.getState() == State.INITIAL) {
adapter.notifyDataSetChanged()