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(options, opts)

Or import directly the specific function:


_10
import { subscribe } from "@onflow/sdk"
_10
_10
subscribe(options, 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

options

  • Type: SubscribeParams

_10
export 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

Returns

Subscription


Rate this page