【发布时间】:2020-03-15 16:12:43
【问题描述】:
以下管道:
enum MyError: Error {
case oops
}
let cancel = Fail<Int, Error>(error: MyError.oops)
.print("1>")
.print("2>")
.sink(receiveCompletion: { status in
print("status>", status)
}) { value in
print("value>", value)
}
输出:
1>: receive subscription: (Empty)
2>: receive subscription: (Print)
2>: request unlimited
1>: request unlimited
1>: receive error: (oops)
2>: receive error: (oops)
status> failure(__lldb_expr_126.MyError.oops)
问题
但是,如果我将 receive(on:) 运算符插入到上一个管道中:
enum MyError: Error {
case oops
}
let cancel = Fail<Int, Error>(error: MyError.oops)
.print("1>")
.receive(on: RunLoop.main)
.print("2>")
.sink(receiveCompletion: { status in
print("status>", status)
}) { value in
print("value>", value)
}
输出是:
1>: receive subscription: (Empty)
1>: receive error: (oops)
receive 运算符似乎使管道短路。我还没有看到其他发布者发生这种情况,就在我使用Fail 或PassthroughSubject 发布者时。
这是预期的行为吗?如果有,是什么原因造成的?
解决方法
以下是创建与 receive(on:) 发布者一起使用的失败发布者的示例:
struct FooModel: Codable {
let title: String
}
func failPublisher() -> AnyPublisher<FooModel, Error> {
return Just(Data(base64Encoded: "")!)
.decode(type: FooModel.self, decoder: JSONDecoder())
.eraseToAnyPublisher()
}
let cancel = failPublisher()
.print("1>")
.receive(on: RunLoop.main)
.print("2>")
.sink(receiveCompletion: { status in
print("status>", status)
}) { value in
print("value>", value)
}
【问题讨论】: