Michael Voline
Michael Voline

Reputation: 383

RxSwift observe array change only when appended new element

Is there a way to subscribe to array change only when a new element is appended?

So I want the following closure to be executed only when a new element is appended.

array.asObservable().subscribe(onNext: { array in

}).disposed(by: self.bag)

If, for example, an element is removed from this array, I don't want this closure to be executed.

EDIT:

Is there a way to only have newly appended elements in the closure? In my case I append subsequences of various lengths, so I can't just look at the last element of the array inside the closure.

Upvotes: 1

Views: 2955

Answers (2)

MiXen
MiXen

Reputation: 125

In that case you should resign using Variable and use Subjects. I think, that your requirements should meet PublishSubject:

let subjectArray = PublishSubject<[Int]>([])
array.asObservable().subscribe(onNext: {
            print($0)
        }).disposed(by: disposeBag)

When you add new elements to subjectArray only that new elements will be printed.

Upvotes: 0

Nour
Nour

Reputation: 122

Maybe something like this

 let array = Variable<[Int]>([])
        array.asObservable().distinctUntilChanged { $0.count > $1.count}.subscribe(onNext: {
            print($0)
        }).disposed(by: disposeBag)

        array.value.append(1) //called
        array.value.append(2) //called
        array.value.remove(at: 0) //not called
        array.value.append(3) //called

Upvotes: 3

Related Questions