Stream conversations and messages with XMTP
XMTP supports real-time message delivery and retrieval. Once you initially retrieve existing conversations, you can listen for a real-time stream of new conversations and messages.
Listen for new conversations
You can code your app to listen for new conversations in real time. Listening for new conversations lets your app display incoming messages from new contacts.
JavaScript
const stream = await xmtp.conversations.stream();
for await (const conversation of stream) {
console.log(`New conversation started with ${conversation.peerAddress}`);
// Say hello to your new friend
await conversation.send("Hi there!");
// Break from the loop to stop listening
//This stream will continue infinitely. To end the stream,
//You can either break from the loop, or call `await stream.return()`.
break;
}
Listen for new messages in a conversation
You can code your app to listen for new incoming and outgoing messages in a conversation by calling conversation.streamMessages()
. The stream returned by the stream
methods is an asynchronous iterator. This means that the stream can be used by a for-await-of loop.
JavaScript
const conversation = await xmtp.conversations.newConversation(
"0x3F11b27F323b62B159D2642964fa27C46C841897",
);
for await (const message of await conversation.streamMessages()) {
if (message.senderAddress === xmtp.address) {
// This message was sent from me
continue;
}
console.log(`New message from ${message.senderAddress}: ${message.content}`);
}
Listen for new messages in all conversations
JavaScript
for await (const message of await xmtp.conversations.streamAllMessages()) {
if (message.senderAddress === xmtp.address) {
// This message was sent from me
continue;
}
console.log(`New message from ${message.senderAddress}: ${message.content}`);
}