Search code examples
swiftrx-swift

How to subscribe on array changes using RxSwift?


I have a simple array:

var similarObjects: [Objects] = []

How I can see his changes after:

similarObjects = someArray

I try: (result: next -> complete)

_ = Observable.just(similarObjects)
     .subscribe({ event in
         return print(event.element)
     })

Solution

  • In order to observe changes for your similarObjects , you have to make it of type Observable...

    So for example you declare similarObjects as follow:

    var similarObjects: PublishSubject<[Objects]> = PublishSubject<[Objects]>()

    And you can subscribe to it by:

    similarObjects
       .asObservable()
       .subscribe(onNext:{
             print($0)
       }
    

    And when you want to assign it a value, you can use onNext operator

    Example:

    similarObjects.onNext(someArray)
    

    By calling onNext, print($0) statement will be executed, make sure to subscribe before calling onNext to your Subject..