Step 4: Publish and Subscribe to Platform Events

Use the Java examples for the Subscribe RPC and PublishStream RPC to try out publishing and receiving events.

Prerequisites

  • If you're using a Developer Edition org and have set up a namespace prefix, modify the Java code that builds the event record to prepend the namespace prefix to the platform event fields. In java/src/main/java/utility/CommonContext.java, modify the two createCarMaintenanceRecord() methods to include the namespace prefix in the field names.
  1. In a Terminal window, return to the top-level java folder.

  2. To run the Subscribe RPC example, enter: ./run.sh genericpubsub.Subscribe

    1. The example subscribes to the five events that were published.
  3. The Subscribe example prints out logging info on the terminal, similar to:

    Because no events were published, the count of received events is zero.

  4. To run the PublishStream RPC example, open another Terminal window. Go to the java folder and then enter ./run.sh genericpubsub.PublishStream

    1. The example publishes five events as set in the arguments.yaml file's default configuration.
  5. The PublishStream example publishes five events by default. It prints out logging information to the terminal similar to this example.

  6. Return to the terminal for the Subscribe example. The output shows the events received.

For more information about the PublishStream and Subscribe RPC methods, see PublishStream RPC Method and Subscribe RPC Method in the Pub/Sub API documentation.

The client code for the Pub/Sub API RPC methods is in the genericpubsub folder. To check out the implementation for each RPC method, open the corresponding Java file in the genericpubsub folder. For example, for the PublishStream example, open PublishStream.java. And for the Subscribe example, open Subscribe.java. For the limitations of the example code, see Limitations in the Readme page of the pub-sub-api GitHub repository.

To run other RPC methods, use this command format: ./run.sh <package_name>.<example_class_name>