简体   繁体   中英

RxSwift onNext not calling scan

I am trying to create a UICollectionView , so that I can add and delete items from it's data source as a Driver. I have a viewModel below

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))
    }
}

}

but .scan closure is never being called, even though actions.onNext is being called in setup , therefore Driver's value is always empty.

It seems like I am getting some core concepts wrong, what might be the problem here?

Just because you have actions.onNext(.add(item: group)) doesn't mean this sequence has started. You are publishing events to a subject that hasn't started. You must have a subscriber somewhere first for assets . Then only scan will get executed. Because observables are pull driven sequences. There must be a subscriber to even make them start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM