Search code examples
iosswiftfor-loopsubscriptionrx-swift

RxSwift Multiple subscriptions to same Observable in for-loop


I need to execute a task multiple times inside a for-loop. The task itself returns Observable<Void>. I feel that I may run into some unexpected errors by continuously subscribing. Is it okay to subscribe n times in for-loop?

private func removeItem(from locations: Resource...) {
    for resource in locations {
        RemoveItemTask(id: item.value.id, resource: resource)
            .execute(in: self.dispatcher)
            .subscribe { event in
                if let error = event.error {
                    self.error = Observable.of(error)
                }
            }.addDisposableTo(self.disposeBag)
    }
}

Solution

  • Why do you want to use a for-loop? RxSwift has a lot of interesting solutions you can use.

    So you have some tasks, you can map them into an array of observables without calling subscribe:

    let observables: [Observable<Void>] = locations.map({ ... })
    

    And then handle all the errors:

    Observable
        .merge(observables.map({ $0.materialize() }))
        .flatMap({ Observable.from(optional: $0.error) })
        .subscribe(onNext: { (error) in
            // Handle error
        })
        .disposed(by: disposeBag)