Skip to content

Instantly share code, notes, and snippets.

@rickclephas
Created August 7, 2022 14:11
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 rickclephas/4c2ab99add21688001168886f759fa50 to your computer and use it in GitHub Desktop.
Save rickclephas/4c2ab99add21688001168886f759fa50 to your computer and use it in GitHub Desktop.
ObservedNativeFlow property wrapper
import Combine
import KMPNativeCoroutinesCore
import KMPNativeCoroutinesCombine
import SwiftUI
class ObservablePublisher<Output>: ObservableObject {
@Published var value: Output
init(_ publisher: AnyPublisher<Output, Never>, _ initialValue: Output) {
value = initialValue
publisher.receive(on: RunLoop.main).assign(to: &$value)
}
}
@propertyWrapper
struct ObservedNativeFlow<Value, Output, Failure: Error, Unit>: DynamicProperty {
@ObservedObject private var publisher: ObservablePublisher<Value>
init(
wrappedValue: Value,
_ nativeFlow: @escaping NativeFlow<Output, Failure, Unit>,
_ transform: (AnyPublisher<Output, Failure>) -> AnyPublisher<Value, Never>
) {
let publisher = transform(createPublisher(for: nativeFlow))
self.publisher = ObservablePublisher(publisher, wrappedValue)
}
var wrappedValue: Value {
get {
return publisher.value
}
}
}
import SwiftUI
import NativeCoroutinesSampleShared
struct ClockView: View {
@ObservedNativeFlow(Clock().timeNative, {
$0.map { time -> String in
let formatter = DateFormatter()
formatter.setLocalizedDateFormatFromTemplate("HH:mm:ss")
let date = Date(timeIntervalSince1970: time.doubleValue)
return formatter.string(from: date)
}
.assertNoFailure()
.eraseToAnyPublisher()
}) var time: String = "--:--:--"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment