Created
September 18, 2024 06:54
-
-
Save curioustechizen/28185f6baece1005e6f3671ba0cf070e to your computer and use it in GitHub Desktop.
KMP-Swift: Return a Flow from Swift
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
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() | |
} | |
} | |
} | |
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
// 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