Arjan van Wieringen
07/01/2022, 5:23 PMMutableSharedFlow
? What I mean is, that I have a routine that both subscribes and emits to the flow. Why would I want this? Well, for instance when I want to send/receive from a Browser BroadcastChannel
:
inline fun <reified T> MutableSharedFlow<T>.broadcast(
channel: BroadcastChannel,
scope: CoroutineScope,
serializersModule: SerializersModule = EmptySerializersModule
) {
val jsonSerializer = Json {
this.serializersModule = serializersModule
}
channel.onmessage = { event ->
val deserialized = jsonSerializer.decodeFromString<T>(event.data as String)
scope.launch {
this@broadcast.emit(deserialized.data)
}
}
this.onEach { data ->
val serialized = jsonSerializer.encodeToString(data)
channel.postMessage(serialized)
}.launchIn(scope)
}
Of course, this will not work and will generate an endless loop, since it receives its own updates. A few options came to my mind:
• remember the last send message - will not work because it can be the case that it receives something again from the broadcastchannel
• create a new wrapper class that overrides 'emit' so that I get a split between internal and external emits and can handle it according to this
• wrapping the sharedflow with some sort of ID and include this ID in the message in order to distinguish own messages, however this dirties the messaging classes, but IMHO I can't find another idea. It leaks the implementation of broadcasting out of the MutableSharedFlow.
Any ideas out there? I can't imagine I am the only one doing this, or I am barking up the completely wrong tree by using MutableSharedFlow 😉ephemient
07/01/2022, 5:29 PMArjan van Wieringen
07/02/2022, 5:49 AMArjan van Wieringen
07/02/2022, 5:52 AM