[英]How to get rid of initial value of Variable in RxSwift
I have been working on RxSwift, I am using a Variable
in RxSwift which is hooked(bind to) to UICollectionView
. 我一直在RxSwift上工作,我在RxSwift中使用了一个
Variable
,该Variable
已挂钩(绑定到) UICollectionView
。 Now knowing that Variable
extends from Behavior Subjects
I had to create a Variable
with some dummy initial value. 现在知道
Variable
是Behavior Subjects
扩展,因此我必须创建一个具有一些虚拟初始值的Variable
。
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) MyDataModel
是一个将json
作为初始化参数的结构(因为MyModel与下面的问题无关,因此不在此处发布其结构)
Now, when I hook it to collectionView, I know that I should ignore the first signal emitted so I use skip(1)
现在,当我将其挂接到collectionView时,我知道我应该忽略发出的第一个信号,所以我使用
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
的第一次更改被忽略,但是当我稍后将实际数据附加到myArray
使用
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
) 它发出通知,但不幸的是,这次
myArray.value
有两个值(虚假的是我在初始化时添加的,另一个实际上是在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. 因此,作为一种变通办法,我要做的是在将数据盲目附加到
myArray.value
之前,检查它是否添加了虚拟对象,如果是,则将其删除并添加实际对象。
Though work around works, makes my code looks very ugly and non Rx in a way. 尽管可以解决问题,但使我的代码在某种程度上看起来非常丑陋且非Rx。 I believe there must be a proper way to deal with it as it is a very fundamental problem working with
Variable
. 我相信必须有一种适当的方法来处理它,因为使用
Variable
是一个非常基本的问题。
I would really appreciate your thoughts on the same. 我真的很感谢您对同样的想法。
First of all, Variable is deprecated in RxSwift 4.x in favor of BehaviorRelay . 首先,在RxSwift 4.x中不推荐使用Variable,而推荐使用BehaviorRelay 。
But for your purpose, PublishSubject or BehaviorSubject (if you need to cache the latest value) should suffice. 但是出于您的目的, PublishSubject或BehaviorSubject (如果您需要缓存最新值)就足够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.