Subscribe to the Channel and Receive the Filtered Event Stream
After configuring the filter, subscribe to the channel and receive the event messages that match the filter expression. Only Pub/Sub API and CometD clients support stream filtering. Because Apex triggers, flows, and processes don’t support custom channels, you can’t use them to subscribe to filtered event streams.
Before subscribing to the channel, follow the steps in the previous sections to create the MyChannel__chn channel, and configure a filter expression for Order_Event__e with Tooling API or Metadata API.
In this example, we use a Pub/Sub API Java client sample. See Java Quick Start for Publishing and Subscribing to Events in the Pub/Sub API Developer Guide. If you prefer to use a tool in the Salesforce UI, you can use the empApi Lightning component or the Streaming Monitor app from AppExchange.
-
Set up the Pub/Sub API Java client and subscribe to the channel.
-
Follow the steps in Java Quick Start for Publishing and Subscribing to Events in the Pub/Sub API Developer Guide.
-
In Step 3: Configure Client Parameters, for the
TOPICargument, provide the custom channel that you created:/event/MyChannel__chn. The channel name format is/event/ChannelName__chn. -
From the java folder, run:
./run.sh genericpubsub.Subscribe.
-
-
Now that you’re subscribed to the custom channel, publish event messages.
-
Open another Terminal window.
-
Navigate to your local
pub-sub-apifolder. -
In an IDE, such as Visual Studio Code, open
java/src/main/java/utility/CommonContext.java. -
Modify the
createEventMessagesmethod. Replace the code with this snippet. Replace theCreatedByIdvalue with your Salesforce user ID. See Find the Salesforce ID for a User or Profile. -
For the configuration parameters in
java/src/main/resources/arguments.yaml, supply these values.TOPIC: /event/Order_Event__eNUMBER_OF_EVENTS_TO_PUBLISH: 5SINGLE_PUBLISH_REQUEST: true
-
Build the client from the top-level java folder with this command:
mvn clean install. -
To run the PublishStream RPC example and publish five event messages from the java folder, enter
./run.sh genericpubsub.PublishStream.As a refresher, here’s the filter expression that we set in the previous section.
From the event messages published, only the second and fourth event messages match the filter criteria given in the previous example and are delivered to the client. The other event messages only partially match the criteria, so they aren’t delivered to the client.
This example shows the two event messages received after subscribing to the filtered channel,
/event/MyChannel__chn.
-