Reputation: 185
I want to keep track of the size of an array, I thought something like this would work:
class CarListViewModel: ObservableObject {
private var cancellables = Set<AnyCancellable>()
@Published var ownedCarLength = 0
init(){
CarRepository.$ownedCars.sink { _ in
self.ownedCarLength = CarRepository.ownedCars.count
}
.store(in: &cancellables)
}
as this is called each time the array CarRepository.ownedCars
is modified, however the value returned from CarRepository.ownedCars.count evaluates to 0 for some reason. Is there a cleaner way of doing this?
Upvotes: 0
Views: 193
Reputation: 299355
It's difficult to know what CarRepository
and CarRepository.ownedCars
are, but I'm guessing they're something like this:
class CarRepositoryType: ObservableObject {
@Published var ownedCars = []
}
var CarRepository = CarRepositoryType()
The sink is called before ownedCars
is updated. The new value is passed to the sink; you should read it there.
CarRepository.$ownedCars.sink { owned in
self.ownedCarLength = owned.count
}
Upvotes: 1