-
-
Save rickclephas/4c2ab99add21688001168886f759fa50 to your computer and use it in GitHub Desktop.
ObservedNativeFlow property wrapper
This file contains 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 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 | |
} | |
} | |
} |
This file contains 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 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