I have been working on RxSwift, I am using a Variable
in RxSwift which is hooked(bind to) to UICollectionView
. Now knowing that Variable
extends from Behavior Subjects
I had to create a Variable
with some dummy initial value.
var myArray = Variable<[MyDataModel]>([MyDataModel(data: "{:}")])
MyDataModel
is a struct that takes json
as a init parameter.(As MyModel has nothing to with the question that follows am not posting the structure of it here)
Now, when I hook it to collectionView, I know that I should ignore the first signal emitted so I use skip(1)
myArray.asObservable().skip(1).bind(to: collectionView.rx.items(cellIdentifier: "test", cellType: MyCollectionViewCell.self){
//cell implementation
})
Though above code works, it solves the problem partially. Though the first change in the value
of myArray
is ignored, but when I append the actually data to myArray
later using
myArray.value.append(someNewData)
it emits the notification and unfortunately this time myArray.value
has two values (dummy one I added while initializing and one that actually triggered onNext
)
So as a work around, what I do is before blindly appending data to myArray.value
I check if it has dummy object I added, if yes I remove it and add the actual object.
Though work around works, makes my code looks very ugly and non Rx in a way. I believe there must be a proper way to deal with it as it is a very fundamental problem working with Variable
.
I would really appreciate your thoughts on the same.
First of all, Variable is deprecated in RxSwift 4.x in favor of BehaviorRelay .
But for your purpose, PublishSubject or BehaviorSubject (if you need to cache the latest value) should suffice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.