Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Created January 10, 2018 10:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgr-ksmt/fe10b14722ea15e9c55558b4afe7608c to your computer and use it in GitHub Desktop.
Save sgr-ksmt/fe10b14722ea15e9c55558b4afe7608c to your computer and use it in GitHub Desktop.
protocol PushNotificationPayload: Decodable {
}
protocol SubscribeContainer {
func parse(_ json: Data)
}
extension SubscribeContainer {
func parse(_ json: Data) {
}
}
class Tsuchi {
static let shared = Tsuchi()
private init() {}
private struct Container<T: PushNotificationPayload>: SubscribeContainer {
let handler: (T) -> Void
func parse(_ data: Data) {
guard let payload = try? JSONDecoder().decode(T.self, from: data) else {
return
}
handler(payload)
}
}
private struct AnyContainer: SubscribeContainer {
let base: SubscribeContainer
}
private var container: AnyContainer?
func subscribe<T: PushNotificationPayload>(_ type: T.Type, handler: @escaping (T) -> Void) {
let container = Container<T>(handler: handler)
self.container = AnyContainer(base: container)
}
func received() {
guard let container = container else {
return
}
let json = ["name": "Taro"]
container.base.parse(try! JSONSerialization.data(withJSONObject: json, options: []))
}
}
struct TestPayload: PushNotificationPayload {
let name: String
}
Tsuchi.shared.subscribe(TestPayload.self) { (payload) in
print("received: \(payload)")
}
Tsuchi.shared.received() // received: TestPayload(name: "Taro")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment