-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathEventHandler.kt
64 lines (53 loc) · 1.82 KB
/
EventHandler.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package dev.openfeature.sdk.events
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.launch
interface EventObserver {
fun observe(): Flow<OpenFeatureEvents>
}
interface ProviderStatus {
fun getProviderStatus(): OpenFeatureEvents
}
interface EventsPublisher {
fun publish(event: OpenFeatureEvents)
}
inline fun <reified T : OpenFeatureEvents> EventObserver.observe() = observe()
.filterIsInstance<T>()
class EventHandler(dispatcher: CoroutineDispatcher) :
EventObserver,
EventsPublisher,
ProviderStatus {
private val sharedFlow: MutableSharedFlow<OpenFeatureEvents> = MutableSharedFlow()
private val currentStatus: MutableStateFlow<OpenFeatureEvents> =
MutableStateFlow(OpenFeatureEvents.ProviderShutDown)
private val job = Job()
private val coroutineScope = CoroutineScope(job + dispatcher)
init {
coroutineScope.launch {
sharedFlow.collect {
currentStatus.value = it
when (it) {
is OpenFeatureEvents.ProviderShutDown -> {
job.cancelChildren()
}
else -> {
// do nothing
}
}
}
}
}
override fun publish(event: OpenFeatureEvents) {
coroutineScope.launch {
sharedFlow.emit(event)
}
}
override fun observe(): Flow<OpenFeatureEvents> = sharedFlow
override fun getProviderStatus(): OpenFeatureEvents = currentStatus.value
}