RxSwift如何附加到BehaviorSubject <[]>

JGu*_*Guo 5 swift rx-swift

由于在RxSwift 4中不推荐使用Variable BehaviorSubject,因此执行以下操作的等效方法是什么?

let observable = Variable<[Int]>([])
observable.value.append(1)
Run Code Online (Sandbox Code Playgroud)

San*_*eep 17

BehaviorRelay是较新版本 RxSwift中Variable的替代品,它似乎工作方式类似.变量具有属性,该在更改时发出事件.与使用BehaviorRelay的类似,您可以使用底层的accept(:)方法来更改值.

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])
Run Code Online (Sandbox Code Playgroud)

不过,如果你愿意的话,也可以和BeviourSubject一起使用,

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

您可以使用抛出函数值()BehaviorSubject获取最新值,因此将值附加到这样,

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

请注意,您将需要调用onNext传递新的价值BehaviorSubject这并不简单,因为它是与变量BahaviorRelay


iVa*_*run 7

我们还可以使用BehaviorRelay扩展轻松地附加对象:

extension BehaviorRelay where Element: RangeReplaceableCollection {

    func add(element: Element.Element) {
        var array = self.value
        array.append(element)
        self.accept(array)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

self.wishList.add(element: item.element)
Run Code Online (Sandbox Code Playgroud)

WishList 是对象 BehaviorRelay