https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Arjan van Wieringen

07/01/2022, 5:23 PM
What would be a good solution for bidirectional operations on
MutableSharedFlow
? 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
:
Copy code
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 😉
e

ephemient

07/01/2022, 5:29 PM
I think it would be better represented as a pair of `SendChannel`&`ReceiveChannel`
a

Arjan van Wieringen

07/02/2022, 5:49 AM
I thought the Kotlin team recommends using Flows over Channels because of their simpler API?
A lot of the Channel API methods are annotated with @ObsoleteCoroutinesAPI
121 Views