Manually disposing a bag and creating a timer

I was reading through the RxSwift docs and did a little test to see if I understood manual disposing. As the example made a lot of sense I thought it’s not a bad idea to share it online.

So DisposeBag kind of retains all your observables that’s why you add them to a bag all the time when you create them. You probably never get to dispose them manually since the moment the bag gets disposed it also disposes all your observables (magic!).

To test disposing I wrote this:

import UIKit

import RxSwift
import RxCocoa

class ViewController: UIViewController {

    var bag: DisposeBag! = DisposeBag()
    var sig: Observable<Int>!
    override func viewDidLoad() {

        sig = Observable<Int>.interval(1.0, scheduler: MainScheduler.instance)
       {num in
            num * 10
        }).subscribeNext({num in
        let tap = UITapGestureRecognizer(target: self, action: "didTap")

    func didTap() {
        bag = nil

Observable<Int>.interval(:scheduler:) creates a sequence that emits each time the timer fires - in the case of the example above each second the observable emits the next integer number.

I map the value and finally in subscribeNext() I print to the console:


I attached a gesture recognizer to the view controller’s view and when the user taps on the view I destroy the bag:

bag = nil

If you give the code a try you will see that when you tap the view the observable stops emitting because the original bag get destroyed and it automatically disposes of all observables added to it.

Very nice and handy when you need to be sure when a resource is deallocated. Further - how cool is that you can create a timer by simply doing Observable<Int>.interval(:scheduler:)?

Hope that post was helpful, and if you want to get in touch you can find me here

Share this post:

If you'd like to learn how to create professional production apps with RxSwift, the best resource out there is the RxSwift book written by Florent Pillet, Junior Bontognali, Marin Todorov, & Scott Gardner.

It features 20+ chapters covering the basics, the Rx operators, and advanced topics like testing, error handling, and app architecture.

Available from Ray Wenderlich: » Learn more.
Tags// ,