Search code examples
arraysswiftrx-swiftbehaviorsubject

How do I append values fo an observed array in RxSwift


Trying to grasp RxSwift and get stuck on a few things.

var observedData = BehaviorSubject.from([2, 3, 4, 5, 6])
    .map({$0*3}).subscribe(onNext: {
        print("HELLO", $0)
    })

How do I append an extra value to the array, so that the subscription is triggered again?

I tried observedData.onNext and observedData.accept but they don't work.

I also would like to know the difference between

var observedData = BehaviorSubject.from([2, 3, 4, 5, 6])

and

var observedData2 = BehaviorSubject<[Int]>(value: [2, 3, 4, 5, 6])

I first assumed it was different ways of writing the same thing, but I can't use .map on observedData2


Solution

  • something like that should work :

    let subject = BehaviorSubject<[Int]>(value: [2, 3, 4, 5, 6])
    subject.asObservable().map({$0.map({$0*3})}).subscribe(onNext: { print("HELLO", $0) }).disposed(by: disposeBag)
    if var value = try? subject.value() {
        value.append(1)
        subject.on(.next(value))
    }