dev_dev
dev_dev

Reputation: 181

Pass a property from an ObservableObject to another ObObject class?

Given I have the ObservableObject that lives on SwiftUI App as the .environmentObject

final class UserSettings: ObservableObject {
   @AppStorage("defaultTaskDuration") var defaultTaskDuration: Int = 1500
   //... other AppStorages
}

(The user might change the defaultTaskDuration via Preferences...)

How to access this in my viewmodel?

@Observable final class TaskDialogViewModel {
    var taskDuration = 0
    func getDefaultTaskDuration() {
          // access defaultTaskDuration
    }
}

What I'm doing now: I pass the value through the View

struct Dialog: View{
    @EnvironmentObject var userSettings: UserSettings
    @Environment(TaskDialogViewModel.self) private var model

    var body: some View {
        HStack {
            ...
        }
        .onAppear {
            model.taskDuration = userSettings.defaultTaskDuration
        }
    }
}

This works. But I wonder if there's a way without passing it to view?

Upvotes: 0

Views: 112

Answers (0)

Related Questions