检测 @Published 属性的布尔切换是否使用 Combine?

huangapple go评论57阅读模式
英文:

Detect Boolean toggle of @Published property with Combine?

问题

我在Swift中的视图模型上有以下已发布的属性:

@Published var myBool = false

我想要一个仅在myBool切换时触发的触发器。如何使用Combine实现这个目标?

英文:

I have the following published property on my view model in Swift:

@Published var myBool = false

I would like to have a trigger that fires only when myBool toggles.

How would I do that using Combine?

答案1

得分: 1

你需要创建一个订阅以订阅你的已发布属性,但需要确保你跳过第一个值,以确保它仅在值切换时触发。

private var cancellables = Set<AnyCancellable>()
@Published var myBool = false

// ...

init() {
    $myBool
        .dropFirst()
        .sink { newValue in
            print(newValue)
        }
        .store(in: &cancellables)
}
英文:

You need to create a subscription to your published property but you need to make sure you droop the first value to make sure it is only triggered for when the value toggles.

private var cancellables = Set&lt;AnyCancellable&gt;()
@Published var myBool = false

// ...

init() {
    $myBool
        .dropFirst()
        .sink { newValue in
            print(newValue)
        }
        .store(in: &amp; cancellables)
}

</details>



# 答案2
**得分**: 0

`@Published`属性在Combine中也是一个发布者,只需将其传递给`sink`。

```swift
private var subscriptions = Set<AnyCancellable>()

$myBool.sink { value in
    print(value)
}
.store(in: &subscriptions)
英文:

A @Published property is also a publisher in terms of Combine, just sink it

private var subscriptions = Set&lt;AnyCancellable&gt;()

$myBool.sink { value in
    print(value)
}
.store(in: &amp;subscriptions)

huangapple
  • 本文由 发表于 2023年6月22日 02:18:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76526108.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定