Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Select specific IPC messages #1069

Closed
ehmicky opened this issue May 19, 2024 · 0 comments · Fixed by #1076
Closed

Select specific IPC messages #1069

ehmicky opened this issue May 19, 2024 · 0 comments · Fixed by #1076

Comments

@ehmicky
Copy link
Collaborator

ehmicky commented May 19, 2024

Background

A very common IPC pattern is to retrieve a message, but only when it matches a specific shape. For example, if messages have a type field, only events of a specific type.

This is currently easy to do with subprocess.getEachMessage().

for await (const message of subprocess.getEachMessage()) {
  if (message.type === 'example') {
    // ...
  }
}

When async iterator helpers will be available in Node, the following functional alternative will be available too:

for await (const message of subprocess
  .getEachMessage()
  .filter(message => message.type === 'example')) {
  // ...
}

Problem

However, it is currently not simple to do the same with subprocess.getOneMessage(), i.e. when retrieving only one message this way.

Using a while loop is slightly cumbersome. But more importantly, if multiple messages are received at the same time (more precisely, if the message event if emitted multiple times in a single tick), then some messages will be lost and never received.

let message;
while (true) {
  message = await subprocess.getOneMessage();
  if (message.type === 'example') {
    break;
  }
}

Solution

Adding a filter option to subprocess.getOneMessage().

const message = await subprocess.getOneMessage({filter: message => message.type === 'example'});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant