合并:将闭包转换为 Publisher
Combine: Convert Closure into Publisher
转换方式:
func getResults(completion: ([Result]?, Error) -> Void)
进入
var resultsPublisher: AnyPublisher<[Result], Error>
只是我所看到的方案(此语法不存在):
var resultsPublisher: AnyPublisher<[Result], Error> {
let publisher: AnyPublisher = ... // init
getResults { results, error in
guard let results = results else {
publisher.produce(error: error) // this syntax doesn't exist
return
}
publisher.produce(results: results) // this syntax doesn't exist
}
return publisher
}
我需要它,因为一些 3d 方 SDK 使用 completion closures
,我想为它们编写扩展 return Publishers
.
答案是 Future
出版商 matt
解释说:
var resultsPublisher: AnyPublisher<[Result], Error> {
// need deferred when want
// to start request only when somebody subscribes
// + without Deferred it's impossible to .retry() later
Deferred {
Future { promise in
self.getResults { results, error in
guard let results = results else {
promise(.failure(error))
return
}
promise(.success(results))
}
}
}
.eraseToAnyPublisher()
}
转换方式:
func getResults(completion: ([Result]?, Error) -> Void)
进入
var resultsPublisher: AnyPublisher<[Result], Error>
只是我所看到的方案(此语法不存在):
var resultsPublisher: AnyPublisher<[Result], Error> {
let publisher: AnyPublisher = ... // init
getResults { results, error in
guard let results = results else {
publisher.produce(error: error) // this syntax doesn't exist
return
}
publisher.produce(results: results) // this syntax doesn't exist
}
return publisher
}
我需要它,因为一些 3d 方 SDK 使用 completion closures
,我想为它们编写扩展 return Publishers
.
答案是 Future
出版商 matt
解释说:
var resultsPublisher: AnyPublisher<[Result], Error> {
// need deferred when want
// to start request only when somebody subscribes
// + without Deferred it's impossible to .retry() later
Deferred {
Future { promise in
self.getResults { results, error in
guard let results = results else {
promise(.failure(error))
return
}
promise(.success(results))
}
}
}
.eraseToAnyPublisher()
}