Alexander  Kraynov
Alexander Kraynov

Reputation: 172

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?

Upvotes: 0

Views: 571

Answers (1)

Rukshan
Rukshan

Reputation: 8066

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.

Upvotes: 0

Related Questions