All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.dk.cachet.carp.common.infrastructure.services.EventBusLog.kt Maven / Gradle / Ivy

Go to download

Helper classes and base types relied upon by all subsystems. This library does not contain any domain logic.

The newest version!
package dk.cachet.carp.common.infrastructure.services


import dk.cachet.carp.common.application.services.ApplicationService
import dk.cachet.carp.common.application.services.EventBus
import dk.cachet.carp.common.application.services.IntegrationEvent
import kotlin.reflect.KClass


/**
 * Logs incoming events on an event bus that are requested to be observed.
 */
class EventBusLog( eventBus: EventBus, vararg toObserve: Subscription<*, *> )
{
    data class Subscription<
        TService : ApplicationService,
        TEvent : IntegrationEvent
    >( val eventSource: KClass, val eventType: KClass )
    {
        fun registerHandler( eventBus: EventBus, subscriber: Any, handler: suspend (TEvent) -> Unit ) =
            eventBus.registerHandler( eventSource, eventType, subscriber, handler )
    }


    private val loggedEvents: MutableList> = mutableListOf()

    init
    {
        toObserve.forEach {
            it.registerHandler( eventBus, this ) { event -> loggedEvents.add( event ) }
        }
        eventBus.activateHandlers( this )
    }

    /**
     * Retrieve all elements in the log and clear it after.
     */
    fun retrieveAndEmptyLog(): List> = loggedEvents.toList().also { loggedEvents.clear() }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy