Skip to content

Commit

Permalink
Merge pull request #1018 from appwrite/feat-realtime-heartbeat-for-re…
Browse files Browse the repository at this point in the history
…act-native

feat: realtime heartbeat for react native
  • Loading branch information
christyjacob4 authored Dec 30, 2024
2 parents 4732e40 + a0cce26 commit de6ac72
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions templates/react-native/src/client.ts.twig
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,17 @@ type RealtimeRequestAuthenticate = {

type Realtime = {
socket?: WebSocket;

/**
* Timeout for reconnect operations.
*/
timeout?: number;

/**
* Heartbeat interval for the realtime connection.
*/
heartbeat?: number;

url?: string;
lastMessage?: RealtimeResponse;
channels: Set<string>;
Expand All @@ -63,6 +73,7 @@ type Realtime = {
getTimeout: () => number;
connect: () => void;
createSocket: () => void;
createHeartbeat: () => void;
cleanUp: (channels: string[]) => void;
onMessage: (event: MessageEvent) => void;
}
Expand Down Expand Up @@ -174,6 +185,7 @@ class Client {
private realtime: Realtime = {
socket: undefined,
timeout: undefined,
heartbeat: undefined,
url: '',
channels: new Set(),
subscriptions: new Map(),
Expand All @@ -199,6 +211,17 @@ class Client {
return 60_000;
}
},
createHeartbeat: () => {
if (this.realtime.heartbeat) {
clearTimeout(this.realtime.heartbeat);
}

this.realtime.heartbeat = window?.setInterval(() => {
this.realtime.socket?.send(JSON.stringify({
type: 'ping'
}));
}, 20_000);
},
createSocket: () => {
if (this.realtime.channels.size < 1) {
this.realtime.reconnect = false;
Expand Down Expand Up @@ -237,6 +260,7 @@ class Client {
this.realtime.socket.addEventListener('message', this.realtime.onMessage);
this.realtime.socket.addEventListener('open', _event => {
this.realtime.reconnectAttempts = 0;
this.realtime.createHeartbeat();
});
this.realtime.socket.addEventListener('close', event => {
if (
Expand Down

0 comments on commit de6ac72

Please sign in to comment.