Observe array in Swift 3 using RxSwift

pableiros picture pableiros · Jun 29, 2017 · Viewed 18.3k times · Source

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?

Answer

kamwysoc picture kamwysoc · Jun 29, 2017

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.