【问题标题】:RxSwift onNext not calling scanRxSwift onNext 不调用扫描
【发布时间】:2021-02-22 08:27:27
【问题描述】:

我正在尝试创建一个UICollectionView,以便我可以作为驱动程序从它的数据源中添加和删除项目。我在下面有一个 viewModel

import Photos
import RxCocoa
import RxSwift

class GroupedAssetsViewModel {
enum ItemAction {
    case add(item: PHAssetGroup)
    case remove(indexPaths: [IndexPath])
}

let assets: Driver<[GroupedAssetSectionModel]>
let actions = PublishSubject<ItemAction>()
private let deletionService: AssetDeletionService = AssetDeletionServiceImpl()

init() {
    assets = actions
        .debug()
        .scan(into: []) { [deletionService] items, action in
            switch action {
            case .add(let item):
                let model = GroupedAssetSectionModel()
                items.append(GroupedAssetSectionModel(original: model, items: item.assets))
            case .remove(let indexPaths):
                var assets = [PHAsset]()
                for indexPath in indexPaths {
                    items[indexPath.section].items.remove(at: indexPath.item)
                    assets.append(items[indexPath.section].items[indexPath.row])
                }
                deletionService.delete(assets: assets)
            }
        }
        .asDriver(onErrorJustReturn: [])
}

func setup(with assetArray: [PHAssetGroup] = [PHAssetGroup]()) {
    for group in assetArray {
        actions.onNext(.add(item: group))
    }
}

}

但是.scan闭包永远不会被调用,即使actions.onNextsetup中被调用,因此Driver的值总是空的。

我好像搞错了一些核心概念,这可能是什么问题?

【问题讨论】:

  • 你在某处订阅assets吗?
  • 是的,这就是问题所在,订阅是在设置之后,我没有得到任何结果
  • 这告诉我您的真正问题是您使用PublishSubject 代替actions。您的视图模型中根本不应该有任何主题。它应该是 Observables in, Observables out。

标签: ios swift rx-swift reactivex rx-cocoa


【解决方案1】:

因为你有 actions.onNext(.add(item: group)) 并不意味着这个序列已经开始。您正在向尚未开始的主题发布事件。您必须首先在某处订阅assets。然后只有scan 会被执行。因为 observables 是拉驱动的序列。必须有订阅者才能让他们开始。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-21
    相关资源
    最近更新 更多