Spdollaz
Spdollaz

Reputation: 185

SwiftUI/Combine Are publishers bi-directional?

The execution of this code is confusing me:

class RecipeListViewModel: ObservableObject {
    
    @Published var recipeList = [RecipeViewModel]()
    
    init(){

        RecipeRepository.$allRecipeVMs.map { recipes in
            recipes.map { recipe in
            recipe
            }
        }
        .assign(to: &$recipeList)
    }
}

My understanding was that SwiftUI publishers are uni-directional, meaning that when RecipeRepository.allRecipeVMs is modified recipeList is too. However, the behaviour I'm seeing is that When recipeList is updated, RecipeRepository.allRecipeVMs is also updated. I've tried to find documentation on this but can't seem to find anything.

Here is the RecipeViewModel class, not sure if it's useful:

class RecipeViewModel : Identifiable, ObservableObject, Hashable{
    
    var id = UUID().uuidString
    @Published var recipe: Recipe

    init(recipe: Recipe){

        self.recipe = recipe
    }
}

Upvotes: 0

Views: 204

Answers (1)

Ryan
Ryan

Reputation: 1392

It's not clear what "modifications" you are calling. @Published and SwiftUI views diff value types, whereas you've created an array of reference types. It will diff only when the instance of that object changes, not when the object itself fires its ObjectWillChange publisher.

Frankly, that's a pretty useful setup because you can have containers that distribute and manage dependencies in your app without causing the root view hierarchy to diff and rebuild constantly.

If you want some sort of two-way Delegate relationship, you can simply set a weak variable in the VMs to self.

Upvotes: 2

Related Questions