【问题标题】:Combine assign(to:) with a @Published var将 assign(to:) 与 @Published var 结合使用
【发布时间】:2022-06-16 00:22:15
【问题描述】:

我的项目中有一个枚举:

enum Remote<Content> {
  case .notAsked
  case .loading
  case .loaded(Content)
  case .failed(Error)
}

然后我有课:

class MyViewModel: ObservableObject {
  @Published var content: Remote<ContentStruct> = .notAsked

  func fetchContent() {
    content = .loading

    service.fetchContent()
      .receive(on: queue)
      .map(Remote<ContentStruct>.loaded)
      .catch { error in Just(.failed(error)) }
      .assign(to: &self.content)
  }
}

但这向我抱怨:

Cannot convert value of type 'Remote<ContentStruct>' to expected argument type 'Published<Remote<ContentStruct>>.Publisher'

我可以改变它来使用它:

func fetchContent() {
  content = .loading

  service.fetchContent()
    .receive(on: queue)
    .map(Remote<ContentStruct>.loaded)
    .catch { error in Just(.failed(error)) }
    .assign(to: \.content, on: self)
    .store(in: &cancellables)
}

这可以正常工作并正确分配值。但是我不明白为什么我不能使用那里的.assign(to: keyPath)函数?

我需要做一些不同的事情吗?我们最近才更新以支持最低 iOS14,因此由于内存泄漏之前没有使用assign(to:,现在我不确定它是如何工作的。

谢谢

【问题讨论】:

  • 这个不能编译,因为Remote是两种泛型,而Remote&lt;ContentStruct&gt;只有一种。所以这与真实案例相去甚远。你真的需要帮助或躲猫猫吗?
  • @Asperi 哦,我的坏遥控器只有通用内容。但这会编译并运行。
  • @Asperi 现已修复,请重新投票。谢谢
  • 投诉非常直接。无法将您的自定义类型值分配给发布者。我会研究 .flatMap 来创建一个新的发布者。 developer.apple.com/documentation/combine/…
  • @cora 我尝试了类似.flatMap(Just.init) 的操作,但现在它只是在错误中添加了一层Published&lt;Just&lt;...&gt;&gt;.Publisher。就像我说的,这是我们必须以这种方式正确使用assign 的第一次机会。解决这个问题对你来说可能非常简单,但知道如何解决它会很好。我只是不确定我在这里做错了什么。谢谢

标签: swift combine


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多