Search code examples
iosswiftrx-swiftreactivex

Observe array in Swift 3 using RxSwift


To create an observable array using RxSwift in Swift 2, I use to do this:

[1, 2, 3].toObservable().subscribeNext { print($0) }

But in Swift 3, it doesn't work anymore, I got this error:

Value of type '[Int]' has no member 'toObservable'

How can I create an RxSwift observable array from a swift array?


Solution

  • In Swift 3 using RxSwift 3.0 I will do that like this:

    var array: Variable<[Int]> = Variable([1, 2, 3])
    array.asObservable().subscribe(onNext: {
            updatedArray in
            print(updatedArray)
    })
    array.value.append(4) // it will trigger `onNext` event 
    

    So the main difference is that you have to create an Variable object instead of using an explicit array.