Skip to main content

Subscribing

Subscribing to a stream means to read/consume data/messages from a stream.

Applications publish and subscribe to streams via Streamr nodes. In other words, nodes are the access points to the Streamr Network. You can either run a light node which is imported as a library and runs locally as part of your application (Streamr SDK) or you can interface your app with a Streamr node. The Streamr node runs separately, and your application connects to it remotely using one of the supported protocols, WebSockets, HTTP or MQTT.

Subscribe code snippets

// Run a Streamr node right inside your JS app
const Streamr = require('@streamr/sdk')
const { StreamrClient } = require('@streamr/sdk')

// Initialize the Streamr SDK with an Ethereum account
// If the stream is private then this account will need
// the subscribe permission on this stream to subscribe
const streamr = new Streamr({
auth: {
// If this stream is publicly subscribable you can skip this part
// or use a throwaway accounts with:
// privateKey: StreamrClient.generateEthereumAccount().privateKey,
privateKey: 'ethereum-private-key',
},
});

// Subscribe to the stream of messages
streamr.subscribe(
streamId,
(content, metadata) => { ... }
// Handle incoming messages
}
);

Unsubscribing from a subscription

await streamr.unsubscribe(streamId);
// or, unsubscribe them all:
const streams = await streamr.unsubscribe();

Getting all subscriptions

const subscriptions = streamr.getSubscriptions();