为 SwiftUI Combine 发布者生成错误(失败)的方法
Method to generate error (failure) for a SwiftUI Combine publisher
我正在编写模拟服务来测试 SwiftUI MVVM 项目中的登录。在我的视图模型中:
func login() {
self.cancellable = service.login(email: email, password: password)
.sink(receiveCompletion: { [weak self] completion in
switch completion {
case .finished:
break
case .failure(let error):
if let session = self?.session {
session.currentUser = nil
}
print(error.localizedDescription)
}
}, receiveValue: { user in
if let session = self.session {
session.currentUser = user
}
})
}
我的模拟服务代码:
func login(email: String, password: String) -> AnyPublisher<User, Error> {
let user = User(name: "test", email: email, password: password)
if email.lowercased() == "test@mail.com" && password == "Password!23" {
return Just(user)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
} else {
// ??? How to generate a failure here
}
}
我的问题是如何在我的代码中生成错误(失败)?我只找到了一些关于错误处理的代码示例。但是找不到如何在发布者中生成错误。
有一个 Fail
Combine 发布商可以满足您的需求:
extension String: Error {}
func randomlyFail() -> AnyPublisher<Int, Error> {
Bool.random()
? Fail(error: "random error")
.eraseToAnyPublisher()
: Just(1)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
我正在编写模拟服务来测试 SwiftUI MVVM 项目中的登录。在我的视图模型中:
func login() {
self.cancellable = service.login(email: email, password: password)
.sink(receiveCompletion: { [weak self] completion in
switch completion {
case .finished:
break
case .failure(let error):
if let session = self?.session {
session.currentUser = nil
}
print(error.localizedDescription)
}
}, receiveValue: { user in
if let session = self.session {
session.currentUser = user
}
})
}
我的模拟服务代码:
func login(email: String, password: String) -> AnyPublisher<User, Error> {
let user = User(name: "test", email: email, password: password)
if email.lowercased() == "test@mail.com" && password == "Password!23" {
return Just(user)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
} else {
// ??? How to generate a failure here
}
}
我的问题是如何在我的代码中生成错误(失败)?我只找到了一些关于错误处理的代码示例。但是找不到如何在发布者中生成错误。
有一个 Fail
Combine 发布商可以满足您的需求:
extension String: Error {}
func randomlyFail() -> AnyPublisher<Int, Error> {
Bool.random()
? Fail(error: "random error")
.eraseToAnyPublisher()
: Just(1)
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}