Review generated event registry

from Lambda expressions
Kotlin 2.4.10 advanced 6 min 4 issues to find

Review this generated event registry before it is used in a concurrent service.

Reject blank event names, support concurrent registration and emission, make high-volume unsubscription efficient, and isolate handler failures without logging payloads.

kotlin
class EventRegistry {
    private val handlers =
        mutableMapOf<String, MutableList<(String) -> Unit>>()

    fun on(event: String, handler: (String) -> Unit): () -> Unit {
        val list = handlers.getOrPut(event) { mutableListOf() }
        list += handler
        return { list.remove(handler) }
    }

    fun emit(event: String, payload: String) {
        handlers[event]?.forEach { handler ->
            try {
                handler(payload)
            } catch (error: Exception) {
                println("handler failed for $payload: ${error.message}")
            }
        }
    }
}

generated code is illustrative, not from any one model

Open in playground
Report an error