Swift Combine 如何跳过一个事件

mar*_*mas 0 swift combine

我在我的应用程序中使用了一个用于日志记录页面的表单,并且在页脚上有一个绑定来显示任何错误,如下所示:

内容视图.Swift :

Form { Section(footer: Text(self.viewModel.errorMessage))
Run Code Online (Sandbox Code Playgroud)

视图模型.swift

init() {
    self.isCurrentNameValid
         .receive(on: RunLoop.main)
         .map { $0 ? "" : "username must at least have 5 characters" }
         .assign(to: \.errorMessage, on: self)
         .store(in: &cancelSet)
}
Run Code Online (Sandbox Code Playgroud)

问题是 viewModel 中的分配是在 init 中执行的,所以当我启动我的应用程序时,即使用户还没有尝试写任何东西,它也会显示消息。

Is there a way to skip first event like in RxSwift where you would just .skip(1) in combine framework?

mat*_*att 7

Insert the .dropFirst() operator.

self.isCurrentNameValid
    .dropFirst()
    // ... the rest is as before ...
Run Code Online (Sandbox Code Playgroud)

  • 没问题!我从这本免费的在线书中得到了答案:https://www.apeth.com/UnderstandingCombine/operators/operatorsPartitioners/operatorsprefix.html 我也_写_它,但我仍然必须查阅它,因为我永远记不起任何东西。 (3认同)
  • 如果您已经了解 RxSwift,这将有助于学习Combine https://github.com/CombineCommunity/rxswift-to-combine-cheatsheet (2认同)