0

I'm looking reading from RW book.

.retryWhen { errors in
    return errors.enumerated().flatMap { (attempt, error) -> Observable<Int> in
        if attempt >= maxAttempts - 1 {
            return Observable.error(error)
        }
        return Observable<Int>.timer(Double(attempt + 1), scheduler:
            MainScheduler.instance).take(1)
    }
}

The timer isn’t taking a period Variable so it’s firing once and is not repeating. So why is it doing take(1). I see that happening over a few times in the course of the book.

mfaani
  • 33,269
  • 19
  • 164
  • 293

1 Answers1

1

The take(1) is not necessary here. take(1) would have made sure that the timer doesn't repeat.

The Observable.timer is an operator that emits a value periodically. Unless the period parameter is still nil, in which case a TimerOneOffSink would be created. A TimerOneOffSink emits one element and then completes and gets disposed of.

For example:

Observable<Int>
    .timer(3.0,
           scheduler: MainScheduler.instance)
    .take(10)
    .subscribe(
        onNext:      { print($0) },
        onCompleted: { print("Completed") },
        onDisposed:  { print("Disposed") }
    )

would print:

0
Completed
Disposed

After consulting with Marin Todorov, one of the authors, he confirmed that it must be just an oversight.

The whole idea of the code snippet is to wait between retries using a timer with a duration increasing by 1 second: the result is an incremental back-off strategy with a maximum number of attempts.

ielyamani
  • 17,807
  • 10
  • 55
  • 90
  • If you don’t have the `period` then it’s non-repeating. Doesn’t that make it unnecessary? – mfaani Jun 08 '19 at 13:18
  • @Honey yes it's not. – ielyamani Jun 08 '19 at 18:07
  • So the tutorial is confusing. Right? – mfaani Jun 08 '19 at 18:24
  • @Honey yes. they have probably been using `interval` before some edit, it would have made sense with `take(1)`. Using `take(1)` with a timer that doesn't repeat is not wrong, it's just unnecessary. – ielyamani Jun 08 '19 at 18:34
  • You reached to him on Twitter? FWIW, the extra `take(1)` is on a few examples related to `retryWhen`. It’s not an a single that had that mistake – mfaani Jun 08 '19 at 22:07
  • @Honey Yes. I did mention that. I have the first edition of that book – ielyamani Jun 08 '19 at 22:13
  • right. I was just asking because I wanted to know if he's responsive to tweets from people he doesn't know. I don't know if he knows you... – mfaani Jun 09 '19 at 01:23