Reputation: 423
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
Upvotes: 0
Views: 1721
Reputation: 33967
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.
Upvotes: 2
Reputation: 619
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))
}
Upvotes: 1