我是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")
}
)
)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句