Skip to content

Instantly share code, notes, and snippets.

@curioustechizen
Created September 18, 2024 06:54
Show Gist options
  • Save curioustechizen/28185f6baece1005e6f3671ba0cf070e to your computer and use it in GitHub Desktop.
Save curioustechizen/28185f6baece1005e6f3671ba0cf070e to your computer and use it in GitHub Desktop.
KMP-Swift: Return a Flow from Swift
interface SomeRepo {
val selectedProfileFlow: Flow<String>
}
// iosMain
interface ProfileObserver {
fun startObserving(onChange: (String) -> Unit)
fun stopObserving()
}
// iosMain
class IosRepo(private val profileObserver: ProfileObserver): SomeRepo {
override val selectedProfileFlow: Flow<String> get() = callbackFlow {
profileObserver.startObserving { profile ->
trySend(profile)
}
awaitClose {
profileObserver.stopObserving()
}
}
}
// Example on iOS that uses a Combine Publisher. You could implement it in other ways like for await or delegates or callbacks
class IosProfileObserver: ProfileObserver {
private var cancellables: Set<AnyCancellable>
func startObserving(onChange: @escaping (String) -> Void) {
profilePublisher.sink { profile in
onChange(profile)
}.storeIn(&cancellables)
}
func stopObserving() {
cancellables.forEach { $0.cancel() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment