英文:
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<AnyCancellable>()
@Published var myBool = false
// ...
init() {
$myBool
.dropFirst()
.sink { newValue in
print(newValue)
}
.store(in: & 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<AnyCancellable>()
$myBool.sink { value in
print(value)
}
.store(in: &subscriptions)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论