How would I access a published variable from another class?

How would I access a published variable from another class?

Problem Description:

So I am currently working on my app and have come across a problem where I have to access a published variable in another observable class.

Here is some code on what I am trying to do

class PeriodViewModel: ObservableObject {
    @Published var value = 1

class DataViewModel: ObservableObject {
    @ObservedObject var periodViewModel = PeriodViewModel()

    periodViewModel.value = 1

How would I be able to access the updated variable from periodViewModel in dataViewModel? Thanks.

Solution – 1

[Note]: Ignore all the variables I am just showing the the flow of using different mangers.

Here is an example of function that I am using for my FirebaseDatabaseManage. You can see a clouser is passing into the function parameter. When your firebase insert function response after async you need to call your clouser which I named as completion.

class FirebaseDatabaseManager {
    public func insertRecipe(with recipe: RecipeModel, completion: @escaping (Bool, String) -> Void) {
        let userID = UserDefaultManager.shared.userId
        database.child(!, withCompletionBlock: { error, ref in
            guard error == nil else {
                completion(false, "failed to write to database")
            completion(true, ref.key ?? "no key found")

Now look at my ViewModel class in which I am calling my FirebaseManager method. On calling of completion I am updating my @Publisher Which you can use to update your UI.

class RecipeViewModel: ObservableObject {

  @Publisher var id = 0
    func createRecipe() {
        FirebaseDatabaseManager.shared.insertRecipe(with: self.recipeModel) { status, id in
   = id

Hope this help your in understand your concepts.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.