Swift Language Disposing


Example

After the subscription was created, it is important to manage its correct deallocation.

The docs told us that

If a sequence terminates in finite time, not calling dispose or not using addDisposableTo(disposeBag) won't cause any permanent resource leaks. However, those resources will be used until the sequence completes, either by finishing production of elements or returning an error.

There are two ways of deallocate resources.

  1. Using disposeBags and addDisposableTo operator.
  2. Using takeUntil operator.

In the first case you manually pass the subscription to the DisposeBag object, which correctly clears all taken memory.

let bag = DisposeBag()
Observable.just(1).subscribeNext { 
    print($0)
}.addDisposableTo(bag)

You don't actually need to create DisposeBags in every class that you create, just take a look at RxSwift Community's project named NSObject+Rx. Using the framework the code above can be rewritten as follows:

Observable.just(1).subscribeNext { 
    print($0)
}.addDisposableTo(rx_disposeBag)

In the second case, if the subscription time coincides with the self object lifetime, it is possible to implement disposing using takeUntil(rx_deallocated):

let _ = sequence
    .takeUntil(rx_deallocated)
    .subscribe {
        print($0)
    }