Search code examples
swifttimercombine

Combine: cancel a flat-mapped Timer.publisher


suppose I have

let stream = PassthroughSubject<String?, Never>()
let repeated = stream.flatMap { value in Timer.publish(every: 3, on: .main, in: .default).autoconnect() }

What I want to achieve is to use the Timer.publish function to make a certain operation every 3 seconds if value != nil, and to stop doing it when stream emits nil.

The first part is easily achieved, how to I kill the flat mapped publisher once the subject emits nil?


Solution

  • You need to map and then switchToLatest... Like this:

    let stream = PassthroughSubject<String?, Never>()
    let repeated = stream.map { value in
        value == nil
        ? Empty().eraseToAnyPublisher()
        : Timer.publish(every: 3, on: .main, in: .default).autoconnect().eraseToAnyPublisher()
    }
        .switchToLatest()