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:
_10import * as sdk from "@onflow/sdk"_10_10sdk.subscribe(subscribeParams, opts)
Or import directly the specific function:
_10import { subscribe } from "@onflow/sdk"_10_10subscribe(subscribeParams, opts)
Usage
_34import * as fcl from "@onflow/fcl";_34import { SubscriptionTopic } from "@onflow/sdk";_34_34// Subscribe to events_34const 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_34const 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:_34subscription.unsubscribe();_34blockSubscription.unsubscribe();
Parameters
subscribeParams
- Type:
_10SubscribeParams<T>
opts
(optional)
- Type:
_10{ node?: string; transport?: SdkTransport; }
- Description: Additional options for the subscription
Returns
A subscription object that allows you to manage the subscription (e.g., to unsubscribe later)