corda / net.corda.core.messaging / MessagingService / addMessageHandler

# addMessageHandler

`abstract fun addMessageHandler(topic: String = "", sessionID: Long = DEFAULT_SESSION_ID, callback: (ReceivedMessage, MessageHandlerRegistration) -> Unit): MessageHandlerRegistration`

The provided function will be invoked for each received message whose topic matches the given string. The callback will run on threads provided by the messaging service, and the callback is expected to be thread safe as a result.

The returned object is an opaque handle that may be used to un-register handlers later with removeMessageHandler. The handle is passed to the callback as well, to avoid race conditions whereby the callback wants to unregister itself and yet addMessageHandler hasn't returned the handle yet.

### Parameters

`topic` - identifier for the general subject of the message, for example "platform.network_map.fetch". The topic can be the empty string to match all messages (session ID must be DEFAULT_SESSION_ID).

`sessionID` - identifier for the session the message is part of. For services listening before a session is established, use DEFAULT_SESSION_ID.

`abstract fun addMessageHandler(topicSession: TopicSession, callback: (ReceivedMessage, MessageHandlerRegistration) -> Unit): MessageHandlerRegistration`

The provided function will be invoked for each received message whose topic and session matches. The callback will run on the main server thread provided when the messaging service is constructed, and a database transaction is set up for you automatically.

The returned object is an opaque handle that may be used to un-register handlers later with removeMessageHandler. The handle is passed to the callback as well, to avoid race conditions whereby the callback wants to unregister itself and yet addMessageHandler hasn't returned the handle yet.

### Parameters

`topicSession` - identifier for the topic and session to listen for messages arriving on.