Код: Выделить всё
// In my root view aka Parent View
import SwiftUI
struct RootView: View {
@StateObject private var devices = DevicesViewModel()
var body: some View {
ScrollView {
UnitStatusCard(devicesVM: devices)
}
.onAppear() {
devices.fetchDevices()
}
}
}
// DeviceViewModel.swift - Parent View Model
import Foundation
class DevicesViewModel: ObservableObject {
@Published var models: [Device] = []
private let networkManager = NetworkManager()
init() {
fetchDevices()
}
public func fetchDevices() {
Task {
do {
if let unitId = UserDefaults.standard.string(forKey: kUnit) {
let models = try await networkManager.fetchData(path: "/api/test")
DispatchQueue.main.async {
self.models = models
}
}
} catch {...}
}
}
}
// UnitStatusCard.swift - Child View
struct UnitStatusCard: View {
@StateObject var unitStatusCardVM: UnitStatusCardViewModel
init(devicesVM: DevicesViewModel) {
self._unitStatusCardVM = StateObject(wrappedValue: UnitStatusCardViewModel(devicesVM: devicesVM))
}
var body: some View {
StatusView()
.onAppear() {
unitStatusCardVM.getStatusMeta()
}
}
}
// UnitStatusCardViewModel.swift - Child View Model
class UnitStatusCardViewModel: ObservableObject {
@Published var value: String = "Good"
var devicesVM: DevicesViewModel
init(devicesVM: DevicesViewModel) {
self.devicesVM = devicesVM
}
public func getStatusMeta() {
print(devicesVM.models) // value is [], WHY??
}
}
Однако, когда я передаю результат в свою дочернюю модель представления (
Код: Выделить всё
UnitStatusCardViewModel
Код: Выделить всё
public func getStatusMeta() {
print(devicesVM.models) // value is [], WHY??
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... view-model