11

I'm trying to emit a sequence on a ”pulse” at a given time interval. Totally new to everything Rx, but thought this would do it:

import RxSwift
let db = DisposeBag()

_ = Observable<Int>.interval(1.0, scheduler: MainScheduler.instance)
    .debug("interval")
    .subscribe(onNext: {
        print($0)
    })
    .addDisposableTo(db)

But it only outputs:

2017-09-25 06:12:41.161: interval -> subscribed

And nothing more. What am I not understanding here?

PEZ
  • 16,821
  • 7
  • 45
  • 66

1 Answers1

14

There is nothing wrong with your code. The dispose bag is alive as it should be. However, the playground execution ends as soon as the last instruction is run, hence the problem.

In order to tell the playground to continue running after everything was executed, you have to import PlaygroundSupport and tell the page to continue running:

import RxSwift
import PlaygroundSupport

let db = DisposeBag()

Observable<Int>.interval(1.0, scheduler: MainScheduler.instance)
    .debug("interval")
    .subscribe(onNext: {
        print($0)
    })
    .addDisposableTo(db)

PlaygroundPage.current.needsIndefiniteExecution = true
iska
  • 2,208
  • 1
  • 18
  • 37
  • 3
    in RxSwift5: ```Observable.interval(.seconds(1.0), scheduler: ...``` – yonivav May 05 '19 at 12:33
  • 3
    How could stop this timer? – Hamed Sep 21 '19 at 12:00
  • You create an instance of `var timerDisposable: Disposable?` and return the output if `Observable.interval(.seconds(1.0), scheduler: ...` to `timerDisposable`. Finally you can stop the timer by calling `timerDisposable?.dispose()`. – Maschina Mar 20 '20 at 19:37