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

Commit

Permalink
Merge pull request #37 from spotify/add-dispatchers
Browse files Browse the repository at this point in the history
add dispatchers to the extensions
  • Loading branch information
vahidlazio authored Jul 27, 2023
2 parents 5e52363 + e351147 commit c063d16
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dev.openfeature.sdk.async

import dev.openfeature.sdk.OpenFeatureClient
import dev.openfeature.sdk.Value
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
Expand All @@ -15,9 +16,10 @@ interface AsyncClient {
}

internal class AsyncClientImpl(
private val client: OpenFeatureClient
private val client: OpenFeatureClient,
private val dispatcher: CoroutineDispatcher
) : AsyncClient {
private fun <T> observeEvents(callback: () -> T) = observeProviderReady()
private fun <T> observeEvents(callback: () -> T) = observeProviderReady(dispatcher)
.map { callback() }
.distinctUntilChanged()

Expand Down
15 changes: 10 additions & 5 deletions OpenFeature/src/main/java/dev/openfeature/sdk/async/Extensions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
Expand All @@ -12,20 +13,24 @@ import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine

fun OpenFeatureClient.toAsync(): AsyncClient {
return AsyncClientImpl(this)
fun OpenFeatureClient.toAsync(dispatcher: CoroutineDispatcher = Dispatchers.IO): AsyncClient {
return AsyncClientImpl(this, dispatcher)
}

internal fun observeProviderReady() = EventHandler.eventsObserver()
internal fun observeProviderReady(
dispatcher: CoroutineDispatcher = Dispatchers.IO
) = EventHandler.eventsObserver(dispatcher)
.observe<OpenFeatureEvents.ProviderReady>()
.onStart {
if (EventHandler.providerStatus().isProviderReady()) {
this.emit(OpenFeatureEvents.ProviderReady)
}
}

suspend fun awaitProviderReady() = suspendCancellableCoroutine { continuation ->
val coroutineScope = CoroutineScope(Dispatchers.IO)
suspend fun awaitProviderReady(
dispatcher: CoroutineDispatcher = Dispatchers.IO
) = suspendCancellableCoroutine { continuation ->
val coroutineScope = CoroutineScope(dispatcher)
coroutineScope.launch {
observeProviderReady()
.take(1)
Expand Down

0 comments on commit c063d16

Please sign in to comment.