Search code examples
swiftreactive-programmingrx-swiftrx-cocoacombinelatest

Which rxSwift operator to use in this scenario?


Here is my scenario. I have one Subject that is being used together with another Subject in a combineLatest. So far so good. Now i push onCompleted on one of the Subjects but the CombineLatest is still working when the other subject pushes some event.

What i want is that as soon as either of the subjects has completed i want the combineLatest to stop working. Is CombineLatest the right Operator to use here ? Or is there any other operator available ?


Solution

  • You should use takeUntil operator:

    let subject1 = PublishSubject<Void>()
    let subject2 = PublishSubject<Void>()
    let subjectWasCompleted = Observable<Void>
        .merge(
            subject1.ignoreElements().andThen(.just(())),
            subject2.ignoreElements().andThen(.just(()))
        )
    
    Observable.combineLatest(subject1, subject2)
        .takeUntil(subjectWasCompleted)
        .subscribe()
        .disposed(by: disposeBag)