RxSwift Sequence Lifetime (Disposable)

Updated
Oct 10, 2019 5:30 AM
Created
Oct 10, 2019 5:26 AM
Tags
SwiftRxSwift.framework
Keywords

import RxSwift

class Box {
  let name: String
  init(name: String) {
    self.name = name
  }
  deinit {
    print("Deinit", name)
  }
}

func makeTask(name: String) -> Single<Int> {
  Single<Int>.create { (observer) -> Disposable in
    
    let box = Box(name: name)

    DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
      observer(.success(1))
    }
        
    return Disposables.create {
      box
    }
  }
}

store: do {
  var disposeBag = Optional.some(DisposeBag())
  makeTask(name: "store").debug("store").subscribe().disposed(by: disposeBag!)
  disposeBag = nil
}

noStore: do {
  makeTask(name: "noStore").debug("noStore").subscribe()
}

🛵

2019-10-10 14:26:12.490: store -> subscribed 2019-10-10 14:26:12.534: store -> isDisposed Deinit store 2019-10-10 14:26:12.535: noStore -> subscribed 2019-10-10 14:26:13.610: noStore -> Event next(1) 2019-10-10 14:26:13.610: noStore -> Event completed 2019-10-10 14:26:13.610: noStore -> isDisposed Deinit noStore