RxSwift how to append to BehaviorSubject<[]>

BehaviorRelay is a replacement for Variable in newer versions RxSwift, which seem to work similarly. Variable has a property value which emits event when changed. Similar to that with BehaviorRelay, you can use underlying accept(:), method to change the value.

let array = BehaviorRelay(value: [1, 2, 3])

array.subscribe(onNext: { value in
    print(value)
}).disposed(by: disposeBag)


// for changing the value, simply get current value and append new value to it
array.accept(array.value + [4])

Nevertheless, this can be worked on with BeviourSubject as well if you wish to,

let subject = BehaviorSubject(value: [10, 20])
subject.asObserver().subscribe(onNext: { value in
    print(value)
}).disposed(by: disposeBag)

You can get latest value from BehaviorSubject with a throwing function value(), and so appending the value with look like this,

do {
    try subject.onNext(subject.value() + [40]) // concatenating older value with new 
} catch {
    print(error)
}

Notice that you would need to call onNext to pass new value to BehaviorSubject which is not as simple as it is with Variable or BahaviorRelay


We can also use BehaviorRelay extension to append objects easily:

extension BehaviorRelay where Element: RangeReplaceableCollection {

    func add(element: Element.Element) {
        var array = self.value
        array.append(element)
        self.accept(array)
    }
}

Usage:

self.wishList.add(element: item.element)

wishList is object of BehaviorRelay

Tags:

Swift

Rx Swift