Spdollaz
Spdollaz

Reputation: 185

How can I subscribe to the size of an array in SwiftUI?

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

Answers (1)

Rob Napier
Rob Napier

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

Related Questions