Last active
March 24, 2024 06:02
-
-
Save markmals/3ced194c7fb891085b6f1bd3ca61a6e4 to your computer and use it in GitHub Desktop.
An implementation of Solid.js's signals API using Swift's @observable macro
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 | |
import Observation | |
@Observable | |
final class Signal<T> { | |
var value: T | |
init(value: T) { | |
self.value = value | |
} | |
} | |
public func createSignal<T>(_ initialValue: T) -> (() -> T, (T) -> Void) { | |
let signal = Signal(value: initialValue) | |
return ( | |
{ return signal.value }, | |
{ newValue in signal.value = newValue } | |
) | |
} | |
public func createEffect(_ apply: @escaping () -> Void) { | |
@Sendable func observe() { | |
withObservationTracking { | |
apply() | |
} onChange: { | |
DispatchQueue.main.async { | |
observe() | |
} | |
} | |
} | |
observe() | |
} | |
enum Box<T>: RawRepresentable { | |
case initialized(T) | |
case uninitialized | |
var rawValue: T { | |
switch self { | |
case .initialized(let value): return value | |
case .uninitialized: fatalError("Memoized function accessed before initialization") | |
} | |
} | |
init(rawValue: T) { | |
self = .initialized(rawValue) | |
} | |
} | |
public func createMemo<T: Equatable>(_ computation: @autoclosure @escaping () -> T) -> () -> T { | |
let signal = Signal<Box<T>>(value: .uninitialized) | |
createEffect { | |
let value = computation() | |
guard case .initialized(_) = signal.value else { | |
signal.value = .initialized(value) | |
return | |
} | |
if value != signal.value.rawValue { | |
signal.value = .initialized(value) | |
} | |
} | |
return { return signal.value.rawValue } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: