Search code examples
swiftreactive-cocoareactive-cocoa-4

Retry after delay if signal doesn't send next in ReactiveCocoa 4


I am using ReactiveCocoa 4.0 with Swift. I have a signal called startedSignal of type Signal<String, NoError> that I subscribe to in a view controller.

startedSignal.observeNext { _ in
  // Do stuff
}

I basically want to wait a number of seconds, then do something else if startedSignal doesn't send in any next values. I looked at the docs and saw things like retry on SignalProducer but I am not sure how that can be used to achieve this, given that startedSignal doesn't complete or send errors.


Solution

  • While Rex is useful if you have some more advanced use cases and you don't want to implement this logic yourself, you can actually do this with the existing operators in ReactiveCocoa, using a combination of timeoutWithError and flatMapError or retry:

    signal
       .promoteErrors(Error.self)
       .timeoutWithError(
          .Timeout, 
          afterInterval: interval,
          onScheduler: QueueScheduler()
       )
       .flatMapError { error in
          return anotherProducer
       }
    
      // Somewhere else:
      private enum Error: ErrorType {
        case Timeout
      }