要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
。
这个观察集合工作方式就像任何其他的提供集合更改事件(插入和删除)一样。区别在于,每个元素必须实现下面讨论的 NotifyChanged 协议。这样,不仅可以在元素插入时接收事件,还可以在修改变量时接收实现 NotifyChanged 协议的对象的事件。
protocol NotifyChanged: class {
func raiseChangeFor<A>(keyPath: AnyKeyPath, old:A, new:A)
func set<A>(keyPath: ReferenceWritableKeyPath<Self, A>, value: A)
var elementChanged: PublishSubject<(keyPath: AnyKeyPath, old:Any, new:Any)>{ get }
}
此协议真正值得注意的是它只有一个,并且是这个通用的集合方法,可以在以下方式中使用。
elements.set(keyPath: \something.money, value: 100)
/// you can use the set method to set any variable in your class this method emits an event on the obeservable collection letting the subscriber that an element in the observable collection has changed.
///
NOTE:
elements.money = 100 //does not emit collection changed event
完整示例
final class something:NotifyChanged { //any class that inherits this must be a final class probably because im still a n0_ob
var elementChanged: PublishSubject<(keyPath: AnyKeyPath, old: Any, new: Any)>
var string:String
var int:Int
var money: Double
init(string:String,int:Int, money:Double) {
self.string = string
self.int = int
self.money = money
elementChanged = PublishSubject<(keyPath: AnyKeyPath, old: Any, new: Any)>()
}
}
var t = ObservableCollection<something>()
t.subscribe(onNext: { [weak self] (tuple) in
// tuple is a combination of the following
// event: which is an enum holding the changed indices
// element: an array of the updated objects in your observable collection
guard let strongSelf = self else { return }
switch tuple.event {
case .deletedIndices(let indices):
DispatchQueue.main.async {
//TODO: Some UI stuff can go here
}
break
case .updatedIndices(let indices):
break
case .insertedIndices(let indices):
break
}
}).disposed(by: disposeBag)
var elements = something(string: "", int: 0, money: 0.0)
t.append(elements)
elements.set(keyPath: \something.money, value: 100)
/// you can use the set method to set any variable in your class this method emits an event on the obeservable collection letting the subscriber that an element in the observable collection has changed.
///
t.append(something(string: "", int: 0, money: 100.0))
t[1].money = 0 // or set the variable directly note this does not emit an collectionchanged event.
需求
安装
rxObservableCollectionWithObservableElement 通过 CocoaPods 可用。要安装它,只需将以下行添加到您的 Podfile 中
pod 'rxObservableCollectionWithObservableElement'