Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The Why
Targeted events are a runtime extension of event types - by default we provide a limited set of types which we can hook onto but say you have 1000 instances of a Thread BFF which have and manage their own state by hooking onto these events. Each of these instances registers around 10 event listeners but incoming events are usually only meant for one specific instance (based on
messageId
) so that's 1000 instances listening times two (two of those 10 listeners per instance are of the same type) - that's 2k function calls out of which only two will actually process the incoming data because the data was meant for them, the rest will exit early - this approach seems wasteful and at larger scale might slow applications down a quite a bit.The Solution
We can reduce the amount of calls by directly targeting what handlers to call by constructing a special type runtime:
fig.1:
In Thread class we know, that for certain handlers we'd only like to run them if the event payload matches
parentMessageId
(new incoming reply), we don't care about the rest.So knowing the
parentMessageId
at theThread
construction time, we can register our handlers with our pre-defined type:At the same time we should register the
factory
function which instructs the dispatcher how to construct the special type based on the incoming event and store it for the specific type. These factories should be either static methods or simply live outside class scope so their signatures are the same across instances as their outputs should only depend on the input event argument and pre-defined factors (such as event types).Now when it comes to dispatching the handlers, the dispatcher pulls in registered factories by incoming event type, runs them all and after looks for handlers stored by type (now using custom types) and since only two of such event handlers were registered for that type, it runs only two (refer to fig.1). Total of 3 function calls (including the factory call) instead of 2000.