我是新的组合和Sink,然而,我在其中放置的打印似乎没有日志,但行动的结果完成,因为用户是在AWS放大器内创建。
@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
}发布于 2021-01-14 15:40:58
使用.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")
}
)
)
}
}https://stackoverflow.com/questions/65691867
复制相似问题