Skip to content
This repository has been archived by the owner on Sep 13, 2023. It is now read-only.

Commit

Permalink
add suspending function for ease of use the provider ready event
Browse files Browse the repository at this point in the history
  • Loading branch information
vahidlazio committed Jul 21, 2023
1 parent 62dd83c commit f48ded0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ import dev.openfeature.sdk.OpenFeatureClient
import dev.openfeature.sdk.events.EventHandler
import dev.openfeature.sdk.events.OpenFeatureEvents
import dev.openfeature.sdk.events.observe
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine

fun OpenFeatureClient.toAsync(): AsyncClient {
return AsyncClientImpl(this)
Expand All @@ -16,4 +22,28 @@ fun observeProviderReady() = EventHandler.eventsObserver()
if (EventHandler.providerStatus().isProviderReady()) {
this.emit(OpenFeatureEvents.ProviderReady)
}
}
}

suspend fun awaitProviderReady() = suspendCancellableCoroutine { continuation ->
val coroutineScope = CoroutineScope(Dispatchers.IO)
coroutineScope.launch {
observeProviderReady()
.take(1)
.collect {
continuation.resumeWith(Result.success(Unit))
}
}

coroutineScope.launch {
EventHandler.eventsObserver()
.observe<OpenFeatureEvents.ProviderError>()
.take(1)
.collect {
continuation.resumeWith(Result.failure(it.error))
}
}

continuation.invokeOnCancellation {
coroutineScope.cancel()
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package dev.openfeature.sdk.events
sealed class OpenFeatureEvents {
object ProviderReady : OpenFeatureEvents()
object ProviderConfigurationChanged : OpenFeatureEvents()
object ProviderError : OpenFeatureEvents()
data class ProviderError(val error: Throwable) : OpenFeatureEvents()
object ProviderStale : OpenFeatureEvents()
object ProviderShutDown : OpenFeatureEvents()
}

0 comments on commit f48ded0

Please sign in to comment.