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(options, opts)
Or import directly the specific function:
_10import { subscribe } from "@onflow/sdk"_10_10subscribe(options, 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
options
- Type:
SubscribeParams
_10export type SubscribeParams<T extends SubscriptionTopic> = {_10 topic: T_10 args: SubscriptionArgs<T>_10 onData: (data: SubscriptionData<T>) => void_10 onError: (error: Error) => void_10}
opts
(optional)
- Type:
SdkTransport;
- Description: Additional options for the subscription