Apps, communicate within a device#
PubSub is a service for bi-directional communication. In this tutorials, we show how PubSub can be used so that two apps can communicate with each other within a device. In this scenario, the data does not need to be sent out to the cloud to be received by the other app. We will be communicating on the device topic
The subscriber sets up a subscription on a topic.
// filename: pubsub/subscribe_device.toit /// Subscribes to a device topic. import pubsub topic ::= "device:hello-world" main: pubsub.subscribe topic: | msg/pubsub.Message | sender := msg.sender.is_device ? "Device($msg.sender.hardware_id)" : "ExternalSystem($msg.sender.external_name)" print "Received message '$msg.payload.to_string' from $sender" return
The publisher publishes the message
"Hello, World!" on the topic and then terminates.
// filename: pubsub/publish_device.toit /// Publishes a message in the appropriate device topic. import pubsub topic ::= "device:hello-world" main: pubsub.publish topic "Hello, World!"
Running the example#
To run the example, run
subscribe.toit on your default device in a terminal window. Once the program is started, open a second terminal window and run
Both windows are depicted here: