Created
February 16, 2020 09:07
-
-
Save shalyf/f223a980c20846b7f8c8ffc5e4295b15 to your computer and use it in GitHub Desktop.
从 iPlayground 2019 学到的简易版 Swift Combine 框架实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let url = URL(string: "https://www.bing.com")! | |
class Subscriber { | |
let cancel: () -> Void | |
init(cancel: @escaping () -> Void) { | |
self.cancel = cancel | |
} | |
deinit { | |
print("deinit") | |
cancel() | |
} | |
} | |
struct Publisher<Value> { | |
let subscribe: (@escaping (Value) -> Void) -> Subscriber | |
func map<NewValue>(_ transform: @escaping (Value) -> NewValue) -> Publisher<NewValue> { | |
return Publisher<NewValue> { (newValueHandler) in | |
return self.subscribe { (value) in | |
let newValue = transform(value) | |
newValueHandler(newValue) | |
} | |
} | |
} | |
} | |
extension URLSession { | |
func dataTaskPublisher(with url: URL) -> Publisher<Data> { | |
return Publisher { (valueHandler) in | |
let task = self.dataTask(with: url) { (data, response, error) in | |
if let data = data { | |
valueHandler(data) | |
} | |
} | |
task.resume() | |
return Subscriber { task.cancel() } | |
} | |
} | |
} | |
let publisher = URLSession.shared.dataTaskPublisher(with: url) | |
.map({ $0.count }) | |
.subscribe { print($0) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment