问题描述
我正在尝试创建一个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.onNext
,也从未调用setup
闭包,因此Driver的值始终为空。
似乎我弄错了一些核心概念,这可能是什么问题?
解决方法
仅仅因为你有
actions.onNext(.add(item: group))
并不表示此序列已开始。您正在将事件发布到尚未开始的主题。您必须首先在assets
的某个位置有一个订户。然后只有scan
被执行。因为可观察的是拉动序列。必须有一个订阅者才能使他们开始。