【发布时间】: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.onNext在setup中被调用,因此Driver的值总是空的。
我好像搞错了一些核心概念,这可能是什么问题?
【问题讨论】:
-
你在某处订阅
assets吗? -
是的,这就是问题所在,订阅是在设置之后,我没有得到任何结果
-
这告诉我您的真正问题是您使用
PublishSubject代替actions。您的视图模型中根本不应该有任何主题。它应该是 Observables in, Observables out。
标签: ios swift rx-swift reactivex rx-cocoa