Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxSwift how to append to BehaviorSubject<[]>

Tags:

swift

rx-swift

Since Variable is deprecated in RxSwift 4, what is the equivalent way for BehaviorSubject to do the following?

let observable = Variable<[Int]>([])
observable.value.append(1)
like image 777
Jack Guo Avatar asked Mar 12 '18 20:03

Jack Guo


Video Answer


2 Answers

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

like image 158
Sandeep Avatar answered Sep 22 '22 10:09

Sandeep


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

like image 37
iVarun Avatar answered Sep 20 '22 10:09

iVarun