本文介绍了合并。Sink打印不打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚开始使用Combine and Sink,但是我放进去的照片似乎没有记录,但是当用户在AWS Amplify中创建时,操作结果就会完成。
@objc private func createAccountButtonAction(sender: UIButton) {
print("Create Account Button Action")
signUp(password: self.password, email: self.email)
}
func signUp(password: String, email: String) -> AnyCancellable {
let userAttributes = [AuthUserAttribute(.email, value: email)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
let sink = Amplify.Auth.signUp(username: email, password: password, options: options)
.resultPublisher.sink(receiveCompletion: { (authError) in
print("Failed with error: (authError)")
}, receiveValue: { (signUpResult) in
print("Signed Up")
})
return sink
}
推荐答案
当您使用.sink
运算符时,它返回AnyCancellable
类型的标记。当该令牌被销毁时,它对自己调用cancel
,这将销毁它所代表的订阅。您没有保存令牌,因此在订阅有机会传递任何输出之前,SWIFT会立即销毁它。
通常的解决方案是找到一个位置来存储令牌,比如在控制器对象的属性中:
class AccountCreationController: UIViewController {
private var token: AnyCancellable? = nil
// NEW ^^^^^ storage for the AnyCancellable
@objc private func createAccountButtonAction(sender: UIButton) {
print("Create Account Button Action")
signUp(password: self.password, email: self.email)
}
func signUp(password: String, email: String) {
let userAttributes = [AuthUserAttribute(.email, value: email)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
token = Amplify.Auth.signUp(username: email, password: password, options: options)
// NEW ^^^^^ store the AnyCancellable to keep the subscription alive
.resultPublisher.sink(
receiveCompletion: { (authError) in
print("Failed with error: (authError)")
},
receiveValue: { (signUpResult) in
print("Signed Up")
})
}
}
如果您确定永远不想取消订阅(例如,用户不能按取消按钮退出),则可以直接创建Subscribers.Sink
,而不是使用sink
运算符,并使用subscribe
方法为Sink
订阅Publisher
。subscribe
方法不返回AnyCancellable
。Sink
对象本身是Cancellable
,但不是AnyCancellable
,您不必将其存储在任何位置即可保持订阅活动。class AccountCreationController: UIViewController {
@objc private func createAccountButtonAction(sender: UIButton) {
print("Create Account Button Action")
signUp(password: self.password, email: self.email)
}
func signUp(password: String, email: String) {
let userAttributes = [AuthUserAttribute(.email, value: email)]
let options = AuthSignUpRequest.Options(userAttributes: userAttributes)
Amplify.Auth.signUp(username: email, password: password, options: options)
// NEW ^ There is no AnyCancellable to store.
.resultPublisher
.subscribe(
// NEW ^^^^^^^^^^ use the subscribe method instead of sink.
Subscribers.Sink(
// NEW ^^^^^^^^^^^^^^^^ Create a Sink object.
receiveCompletion: { (authError) in
print("Failed with error: (authError)")
},
receiveValue: { (signUpResult) in
print("Signed Up")
}
)
)
}
}
这篇关于合并。Sink打印不打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!