我正在使用SwiftUI遇到这个非常奇怪的问题/错误。在setupSubscription
方法中,我正在创建对subject
的订阅,并将其插入到cancellables
集中。但是,当我打印cancellables
的计数时,我得到零。如果我只是将元素插入其中,该集合怎么能为空?
这大概就是为什么我点击按钮时未调用handleValue
方法的原因。这是控制台的完整输出:
init
begin setupSubscription
setupSubscription subject sink: receive subscription: (CurrentValueSubject)
setupSubscription subject sink: request unlimited
setupSubscription subject sink: receive value: (initial value)
handleValue: 'initial value'
setupSubscription: cancellables.count: 0
setupSubscription subject sink: receive cancel
sent value: 'value 38'
cancellables.count: 0
sent value: 'value 73'
cancellables.count: 0
sent value: 'value 30'
cancellables.count: 0
我在做什么错?为什么我对subject
的订阅被取消了?为什么我点击按钮时handleValue
没有被呼叫?
import SwiftUI
import Combine
struct Test: View {
@State private var cancellables: Set<AnyCancellable> = []
let subject = CurrentValueSubject<String, Never>("initial value")
init() {
print("init")
self.setupSubscription()
}
var body: some View {
VStack {
Button(action: {
let newValue = "value \(Int.random(in: 0...100))"
self.subject.send(newValue)
print("sent value: '\(newValue)'")
print("cancellables.count:", cancellables.count)
}, label: {
Text("Tap Me")
})
}
}
func setupSubscription() {
print("begin setupSubscription")
let cancellable = self.subject
.print("setupSubscription subject sink")
.sink(receiveValue: handleValue(_:))
self.cancellables.insert(cancellable)
print("setupSubscription: cancellables.count:", cancellables.count)
// prints "setupSubscription: cancellables.count: 0"
}
func handleValue(_ value: String) {
print("handleValue: '\(value)'")
}
}
答案 0 :(得分:1)
您只是错误地使用了状态-状态与视图相关,并且只有在呈现视图时(即,在body
上下文中),状态才可用(准备好的后备存储)。在初始化中,还没有状态回存,因此您的可取消对象就消失了。
这是可行的方法(但是我建议将与主题相关的所有内容移到单独的视图模型中)
通过Xcode 12 / iOS 14测试
struct Test: View {
private var cancellable: AnyCancellable?
private let subject = CurrentValueSubject<String, Never>("initial value")
init() {
cancellable = self.subject
.print("setupSubscription subject sink")
.sink(receiveValue: handleValue(_:))
}
var body: some View {
VStack {
Button(action: {
let newValue = "value \(Int.random(in: 0...100))"
self.subject.send(newValue)
print("sent value: '\(newValue)'")
}, label: {
Text("Tap Me")
})
}
}
func handleValue(_ value: String) {
print("handleValue: '\(value)'")
}
}
答案 1 :(得分:0)
你在这里做错了一些事情。
永远不要尝试在 swiftUI 结构中存储东西。每次您的视图更改时,它们都会失效并重新加载。这可能是您的订阅被取消的原因。
对于这种情况,您应该使用具有已发布属性的 ObservableObject 或 StateObject。当 ObservableObjects 或 StateObjects 改变时。包含它们的视图会像使用 @State 或 @Binding 一样重新加载:
// ObservedObjects have an implied objectWillChange publisher that causes swiftUI views to reload any time a published property changes. In essence they act like State or Binding variables.
class ViewModel: ObservableObject {
// Published properties ARE combine publishers
@Published var subject: String = "initial value"
}
然后在您看来:
@ObservedObject var viewModel: ViewModel = ViewModel()
如果您确实需要使用发布者。或者,如果您需要在 observable 对象属性更改时执行某些操作。您不需要使用 .sink。这主要用于使用 combine 的 UIKit 应用程序。 SwiftUI 有一个 .onReceive viewmodifier 可以做同样的事情。
以下是我将上述建议付诸实践:
struct Test: View {
class ViewModel: ObservedObject {
@Published var subject: String = "initial value"
}
@ObservedObject var viewModel: Self.ViewModel
var body: some View {
VStack {
Text("\(viewModel.subject)")
Button {
viewModel.subject = "value \(Int.random(in: 0...100))"
} label: {
Text("Tap Me")
}
}
.onReceive(viewModel.$subject) { [self] newValue in
handleValue(newValue)
}
}
func handleValue(_ value: String) {
print("handleValue: '\(value)'")
}
}