英文:
How do I append values fo an observed array in RxSwift
问题
尝试理解RxSwift
并卡在一些问题上。
如何向数组“追加”一个额外的值,以便“订阅”再次触发?
我尝试过observedData.onNext
和observedData.accept
,但它们不起作用。
我还想知道以下两者之间的区别:
var observedData = BehaviorSubject.from([2, 3, 4, 5, 6])
和
var observedData2 = BehaviorSubject<[Int]>(value: [2, 3, 4, 5, 6])
我最初以为它们是写同一件事的不同方式,但我不能在observedData2
上使用.map
。
英文:
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
答案1
得分: 2
除了 @EtienneJézéquel 给出的答案之外...
public static func ObservableType.from(_:)
函数返回一个 Observable,而 BehaviorSubject.init(value:)
创建一个 BehaviorSubject,必须在你可以对其进行 map(_:)
操作之前将其转换为 Observable。
另外,当你意识到你不是向 BehaviorSubject 包含的数组添加元素,而是使用它发出一个 新的 数组时,这可能会有所帮助。这就是为什么 Etienne 的代码首先使用 value() throws
从主题中复制当前数组,然后将新数组附加到副本中,然后使用 onNext(_:)
将新数组推送到主题中。
最后,不要将主题声明为 var
,它们应该始终是 let
,因为在设置链之后不希望重新设置它们。
英文:
Along with the answer @EtienneJézéquel gave...
The public static func ObservableType.from(_:)
function returns an Observable whereas the BehaviorSubject.init(value:)
creates a BehaviorSubject which must then be converted to an Observable before you can map(_:)
it.
Also, it might help to understand better when you realize you don't append to the array that is contained by the BehaviorSubject, instead you emit a new array using it. That's why Etienne's code first copies the current array out of the subject using value() throws
and appends to the copy and then pushes the new array into the subject using onNext(_:)
.
Lastly, don't make subjects var
s they should always be let
s because you don't want to reseat them after setting up chains to them.
答案2
得分: 1
以下是已翻译的内容:
应该可以这样工作:
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))
}
英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论