0

I had

class PackageModel: ObservableObject {
let id = UUID()
@Published var name: String
@Published var rateLimit: CGFloat

init(name: String, rateLimit: CGFloat) {
    self.name = name
    self.rateLimit = rateLimit
}

}

and viewModel class which contains array of Packages

   final class PackagesListViewModel: ObservableObject {

@Published var packages: [PackageModel] = []

private func startTimerForPackagesLiveUpdates() {
    self.packagesRateLimitUpdateTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] _ in
        self?.packages.forEach({ package in
            let rateLimit = calculateRateLimit()
            package.rateLimit = CGFloat(rateLimit)
        })
    })
}

}

Timer updates every package rateLimit value with some calculated arbitrary value

From this ViewModel connected view i opened another view with one of the package instances

class PackageInfoViewModel: ObservableObject {
@ObservedObject var package: PackageModel

package.$rateLimit.sink { (value) in
        debugPrint(value)
    }.store(in: &bag)

}

In Sink closure I get updates not for package that is in this ViewModel but for all PackageModel class instances.

Im new with SwiftUI and Combine. I don't expect this behaviour. Will be thankful for explanation of how is this working, and how i should work around this problem?

  • “In Sink closure I get updates not for package that is in this ViewModel but for all PackageModel class instances.” Alternative explanation: you have created an instance of`PackageInfoViewModel` for every instance of `PackageModel`. – rob mayoff Nov 18 '21 at 18:09
  • every `PackageModel` has to be wrapped in an `@ObservedObject` in your `View`s so you can see the changes. not in another `ObservableObject` the only SwiftUI wrapper that works in a `class` is `@Published`. Also, `PackagesListViewModel` and `PackageInfoViewModel` for that matter. `ObservableObject`s must be wrapped in an `@ObservedObject`, `@StateObject` or an `@EnvironmentObject` – lorem ipsum Nov 18 '21 at 18:13
  • [This](https://stackoverflow.com/questions/68710726/swiftui-view-updating/68713038#68713038) might help – lorem ipsum Nov 18 '21 at 18:17

0 Answers0