今天這部分很適合用 URLSession.datataskPublisher 介紹
assert()
一樣,不會影響上線運作。let pts = PassthroughSubject<Int, URLError>()
pts
.assertNoFailure()
.sink{_ in}
pts.send(1)
pts.send(completion: .failure(.init(.badURL))) // asserting here
某個角度看的話,是不是很像map!?
let session = URLSession.shared
let wrongURL = URL(string: "https://apple.c")!
let trueURL = URL(string: "https://apple.com")!
let m = session
.dataTaskPublisher(for: wrongURL)
.catch{ _ in
return session.dataTaskPublisher(for: trueURL)
}.sink(receiveCompletion: {print($0)}, receiveValue: {print($0.count,$1.url)})
/* console
60596 https://www.apple.com/
finished
*/
目前還找不到 retry with delay 的方法, 找到更新.
let session = URLSession.shared
let wrongURL = URL(string: "https://apple.c")!
let trueURL = URL(string: "https://apple.com")!
let m = session
.dataTaskPublisher(for: wrongURL)
.retry(1) /// <----------- 嘗試重試上游 n 次, 後繼續下游
.catch{ _ in
return session.dataTaskPublisher(for: trueURL)
}.sink(receiveCompletion: {print($0)}, receiveValue: {print($0.count,$1.url)})
Data
元素轉化成 Decodable 型別.要先轉化上游元素成 Data (Output)
let session = URLSession.shared
let trueURL = URL(string: "https://apple.com")!
let m = session
.dataTaskPublisher(for: trueURL)
.map{d,r in #""1""#.data(using: .utf8)!}
.decode(type: String.self, decoder: JSONDecoder())
.sink(receiveCompletion: {print($0)}, receiveValue: {print($0)})
/* console:
1
finished
*/