10

The ReactiveX.io documentation uses AnonymousDisposable, which was in RxSwift 2.x, but is an unresolved identifier in RxSwift 3.0. What should I use instead?

let source = Observable.create { observer in
  for i in 1...5 {
    observer.on(.Next(i))
  }
  observer.on(.Completed)

  // Note that this is optional. If you require no cleanup you can return
  // NopDisposable.instance
  return AnonymousDisposable {
    print("Disposed")
  }
}

source.subscribe {
  print($0)
}
DavidA
  • 3,112
  • 24
  • 35

3 Answers3

18

To create Observable's in Swift 3,4,5 you have to substitute the old AnonymousDisposable instance with Disposables.create(), like in this way:

let source = Observable.create { observer in
    observer.on(.next(1))
    observer.on(.completed)
    return Disposables.create()
}

If you wanna take some action when the Observable is disposed you can use the one you mention before instead:

return Disposables.create {
    print("Disposed")      
}

I hope this help you.

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
2

Note that this syntax from Swift 2:

NopDisposable.instance

has also been replaced with

Disposables.create() 

Beyond that, it's interesting to note that, under the hood, NopDisposable still exists but is exposed via this create method. Here's the source.

Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
0

Use:

return Disposables.create {
    print("Disposed")      
}
DavidA
  • 3,112
  • 24
  • 35