【问题标题】:SwiftUI/Combine Are publishers bi-directional?SwiftUI/Combine 发布者是双向的吗?
【发布时间】:2021-08-01 20:08:09
【问题描述】:

这段代码的执行让我很困惑:

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

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

我的理解是 SwiftUI 发布者是单向的,这意味着当 RecipeRepository.allRecipeVMs 被修改时,recipeList 也是如此。但是,我看到的行为是当recipeList 更新时,RecipeRepository.allRecipeVMs 也会更新。我试图找到这方面的文档,但似乎找不到任何东西。

这里是RecipeViewModel 类,不确定是否有用:

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

    init(recipe: Recipe){

        self.recipe = recipe
    }
}

【问题讨论】:

  • 您能否附上一个minimal reproducible example 来证明您所描述的内容?例如,我想看看RecipeRepository 中的内容...我对allRecipeVMs 持怀疑态度
  • @jnpdx 我将致力于创建一个可重现的示例,但 allRecipeVMs 是 [RecipeViewModel]。
  • 这是一个危险信号,你有一个由 ObservableObject 组成的 @Published 数组——这不会像你期望的那样工作。

标签: swiftui combine


【解决方案1】:

目前尚不清楚您所调用的“修改”是什么。 @Published 和 SwiftUI 查看不同的值类型,而您已经创建了一个引用类型数组。仅当该对象的实例发生更改时才会有差异,而不是当对象本身触发其 ObjectWillChange 发布者时。

坦率地说,这是一个非常有用的设置,因为您可以拥有在应用程序中分发和管理依赖项的容器,而不会导致根视图层次结构不断变化和重建。

如果您想要某种双向委托关系,您可以简单地将 VM 中的弱变量设置为 self。

【讨论】:

  • 是的,这是正确的,我认为这是Combine 在幕后所做的事情,但是当recipeList 子项的属性发生更改时,RecipeRepository.allRecipeVMs 数组已更新,因为RecipeViewModel 是一个类(引用类型)。
  • 某处的错误可能是以后的功能:) 享受
猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多