Hello,
I have the following Problem:
struct Item {
var foo: Int
init(_ iFoo: Int = 0){
self.foo = iFoo
}
}
class TestObject {
@Published var items = [Item(1), Item(2), Item(3), Item(4)]
private var avg:Double = 0.0{
didSet{
print("didSet: avg: '\(self.avg)'")
}
}
private var cancellableSet: Set<AnyCancellable> = []
private var isItemChangedPublisher: AnyPublisher<[Item], Never>{
self.$items
.eraseToAnyPublisher()
}
init(){
self.isItemChangedPublisher
.map{ items in
var sum = 0
for item in items{
sum += item.foo
}
return Double(sum)/Double(items.count)}
.assign(to: \.avg, on: self)
.store(in: &cancellableSet)
}
func changeItem(at index: Int, to value: Int){
if self.items.count < index{
self.items.append(Item(value))
}else{
self.items[index].foo = value
}
}
func getAvg() -> Double{
//Request: Items changed --> Change Value of avg here
//Set Value of avg only if items has changed AND "Request" is called
// - don't set the new Value if Items has not changed and "Request" is called
// - don't set the new Value if Items has changed, but "Request" is not called
return self.avg
}
}
var bar = TestObject()
bar.changeItem(at: 2, to: 20)
bar.changeItem(at: 0, to: 3)
print("1. avg: '\(bar.getAvg())'")
bar.changeItem(at: 2, to: 20)
print("2. avg: '\(bar.getAvg())'")
bar.changeItem(at: 2, to: 30)
print("3. avg: '\(bar.getAvg())'")
bar.changeItem(at: 2, to: 20)
The Value of var avg
is set every Time I change the items-Array. I understand that this is the intended behavior.
But is there any way to update the Variable avg
only if the items-Array has changed AND something like a "Request" is called. If only the items have been changed the Variable avg
should not be update, also if only the "Request" is called, but no items have been changed, the Variable shouldn't be updated.
I don't have any clue how to do this.
Do you have any idea to do this with the combine framework or with another solution?
I ask the same Question on Stackoverflow, I will keep the posts in sync