Skip to main content

subscribe

Subscribe to real-time data from the Flow blockchain and automatically decode the responses.

This is a utility function used for subscribing to real-time data from the WebSocket Streaming API. Data returned will be automatically decoded via the 'decode' function.

Available topics include: events, blocks, block_headers, block_digests, transaction_statuses, account_statuses.

Import

You can import the entire package and access the function:


_10
import * as sdk from "@onflow/sdk"
_10
_10
sdk.subscribe(subscribeParams, opts)

Or import directly the specific function:


_10
import { subscribe } from "@onflow/sdk"
_10
_10
subscribe(subscribeParams, opts)

Usage


_34
import * as fcl from "@onflow/fcl";
_34
import { SubscriptionTopic } from "@onflow/sdk";
_34
_34
// Subscribe to events
_34
const subscription = fcl.subscribe({
_34
topic: SubscriptionTopic.EVENTS,
_34
args: {
_34
eventTypes: ["A.7e60df042a9c0868.FlowToken.TokensWithdrawn"]
_34
},
_34
onData: (events) => {
_34
console.log("Received events:", events);
_34
},
_34
onError: (error) => {
_34
console.error("Subscription error:", error);
_34
}
_34
});
_34
_34
// Subscribe to blocks
_34
const blockSubscription = fcl.subscribe({
_34
topic: SubscriptionTopic.BLOCKS,
_34
args: {
_34
blockStatus: "finalized"
_34
},
_34
onData: (block) => {
_34
console.log("New block:", block);
_34
},
_34
onError: (error) => {
_34
console.error("Block subscription error:", error);
_34
}
_34
});
_34
_34
// Later, to unsubscribe:
_34
subscription.unsubscribe();
_34
blockSubscription.unsubscribe();

Parameters

subscribeParams

  • Type:

_10
SubscribeParams<T>

opts (optional)

  • Type:

_10
{ node?: string; transport?: SdkTransport; }

  • Description: Additional options for the subscription

Returns

Subscription

A subscription object that allows you to manage the subscription (e.g., to unsubscribe later)


Rate this page