将域与PublishSubject一起使用

问题描述 投票:0回答:1

我想将我的领域结果映射到一个不可变的viewmodel,我想听结果更改,所以我发出它们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
}

在我的演示者中,我使用此observable将模型映射到视图模型,然后我在片段内显示(当订阅时)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)
    }
}

对不起,如果代码不清楚。


编辑:我的onBindViewHolder有时不会被调用(当然,当recyclerview为空时)。

android realm rx-java rx-android publishsubject
1个回答
0
投票

从Realm 5.0开始,初始变更集不再用changeset == null发出信号。

你需要检查:

if(changeSet.getState() == State.INITIAL) {
    adapter.notifyDataSetChanged() 
© www.soinside.com 2019 - 2024. All rights reserved.