I am trying to convert Java Swing events, normally obtained with event listeners, to Kotlin Flow of these events. I checked code of many projects and found more than one way of doing it. I was wondering if someone can give me reasons to use one style over another, in respect to the performance / reliability / resource usage:
fun JButton.actionEvents1(): Flow<ActionEvent> = callbackFlow {
val listener = ActionListener { e ->
trySend(e)
}
addActionListener(listener)
awaitClose {
removeActionListener(listener)
}
}
fun JButton.actionEvents2(): Flow<ActionEvent> = callbackFlow {
val listener = ActionListener { e ->
trySend(e).isSuccess
}
addActionListener(listener)
awaitClose {
removeActionListener(listener)
}
}
fun JButton.actionEvents3(): Flow<ActionEvent> = callbackFlow {
val listener = ActionListener { e ->
trySendBlocking(e)
}
addActionListener(listener)
awaitClose {
removeActionListener(listener)
}
}
fun JButton.actionEvents4(
scope: CoroutineScope
): Flow<ActionEvent> = callbackFlow {
val listener = ActionListener { e ->
scope.launch { send(e) }
}
addActionListener(listener)
awaitClose {
removeActionListener(listener)
}
}
The last example is assuming that we have access to the CoroutineScope
instance, which in my case would be the same scope from which each action events flow is obtained and collect
is called. Should I avoid launching a coroutine for each event?