Advanced reading

First of all, you should create an instance of the SourceReadingSession. It will store information about instantiated ListSource/ListCache and provide smooth experience of reading mails for different list configurations.
const readingSession = new SourceReadingSession();
Then, you can setup reading optimization strategies (if provided for your blockchains):
readingSession.sourceOptimizer = (subject, reader) => {
const useIndexer = true;
if (reader instanceof EthereumBlockchainController) {
const evmListSource = new EthereumListSource(reader, subject, 30000);
if (useIndexer) {
return new IndexerListSource(
evmListSource,
readingSession.indexerHub,
reader,
subject,
);
} else {
return evmListSource;
}
} else {
return new BlockchainListSource(reader, subject, 10000);
}
};
Now, let's setup a reading list. Let it be a combination of direct messages written to the account and messages broadcasted by the same account. It means that we should instantiate two new list sources:
const listSource1 = readingSession.listSource(
{
blockchain,
type: BlockchainSourceType.DIRECT,
recipient: account.uint256Address,
sender: null,
},
reader,
);
const listSource2 = readingSession.listSource(
{
blockchain,
type: BlockchainSourceType.BROADCAST,
sender: account.address,
},
reader,
);
Now, when we have both sources instantiated, we should combine them into one ListSourceMultiplexer. This class is responsible for optimized reading of multiple sources and preserving the correct messages order:
const multiplexer = new ListSourceMultiplexer([listSource1, listSource2]);
After that, we should pass this multiplexer to the ListSourceDrainer. This class is responsible for the accurate loading of the messages in an infinite scroll way.
const list = new ListSourceDrainer(multiplexer);
Okay, we're almost done :) Now, when the preparations are finished, we can actually subscribe to new messages and start reading messages:
list.on('messages', ({ messages }: { messages: IMessageWithSource[] }) => {
console.log(`you've got a new messages, yoohoo: `, messages);
});
await list.resume(); // we need to activate list before we will be able to read from it
const messages = await list.readMore(10); // read 10 more messages. Please note, that this method returns all the messages currently stored in a list (including the new ones)
To check if there are any messages left to read, you can always check drained prop of the ListSourceDrainer:
console.log('can I read more:', list.drained);
if (!list.drained) {
console.log('messages: ', await list.readMore(10));
}
Please, if you want to stop using current list, don't forget to stop all the subscriptions by execting pause method:
list.pause();