Skip to content

Instantly share code, notes, and snippets.

@own2pwn
Created May 3, 2019 16:53
Show Gist options
  • Save own2pwn/633e01d533d56032bc3b2bbfe907858f to your computer and use it in GitHub Desktop.
Save own2pwn/633e01d533d56032bc3b2bbfe907858f to your computer and use it in GitHub Desktop.
Abstract Signal
//
// SharedCache.swift
// Quick-pg
//
// Created by Evgeniy on 01/05/2019.
// Copyright © 2019 surge. All rights reserved.
//
import Foundation
final class SharedCache {
// MARK: - Members
private static var cache: [String: Any] = [:]
// MARK: - Interface
static func set(_ value: Any, for key: String) {
cache[key] = value
}
static func get(key: String) -> Any? {
return cache[key]
}
static func get<T>(key: String) -> T? {
return cache[key] as? T
}
static func remove(key: String) -> Any? {
return cache.removeValue(forKey: key)
}
// MARK: - Init
private init() {}
}
//
// Signal+A.swift
// Quick-pg
//
// Created by Evgeniy on 03/05/2019.
// Copyright © 2019 surge. All rights reserved.
//
import Foundation
private protocol AnyObserver {}
private struct Observer<T>: AnyObserver {
let action: (T) -> Void
}
final class SignalA<T> {
// MARK: - Types
typealias EventBlock = (T) -> Void
private typealias BoxedType = [AnyObserver]
// MARK: - Interface
static func tell(_ sender: T) {
let matched: [Observer<T>] = matchingObservers()
matched.forEach { (observer: Observer<T>) in
observer.action(sender)
}
}
static func listen(handler: @escaping EventBlock) {
let newObserver: Observer<T> = Observer<T>(action: handler)
observers.append(newObserver)
}
// MARK: - Helpers
private static func matchingObservers<T>() -> [Observer<T>] {
return observers.compactMap { $0 as? Observer<T> }
}
// MARK: - Members
private static var observers: BoxedType {
get {
guard let unboxed = SharedCache.get(key: "\(type(of: self))") as? BoxedType else {
return BoxedType()
}
return unboxed
}
set {
SharedCache.set(newValue, for: "\(type(of: self))")
}
}
// MARK: - Init
private init() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment