tRPCttRPC
Powered by
BeBoREB
tRPC•3y ago
BeBoRE

Suspend subscriptions when app is in background

When using React Native, subscriptions stay open even when the app is in the background. While this could be good for some applications, in my use case there is no need to keep the app up to date when in the background.

Using the query client you can make React Query not refetch data using the focusManager's setFocused. Is there a way of telling all subscriptions to end when the app loses focus?
function onAppStateChange(status: AppStateStatus) {
  if (Platform.OS !== 'web') {
    focusManager.setFocused(status === 'active' || status === 'inactive');
  }
}
function onAppStateChange(status: AppStateStatus) {
  if (Platform.OS !== 'web') {
    focusManager.setFocused(status === 'active' || status === 'inactive');
  }
}


I am currently doing this by just setting the enabled option to false whenever the app loses focus. But I would like for this to apply app-wide it feels a bit hacky to have to define this everywhere I'm subbing to something.
const appState = useAppState();

api.lobby.lobbyUpdate.useSubscription(authInfo?.accessToken || '', {
  enabled:
    !!authInfo?.accessToken &&
    (appState === 'active' || appState === 'inactive'),
  onData: (data) => {
    setLobby(data);
  },
});
const appState = useAppState();

api.lobby.lobbyUpdate.useSubscription(authInfo?.accessToken || '', {
  enabled:
    !!authInfo?.accessToken &&
    (appState === 'active' || appState === 'inactive'),
  onData: (data) => {
    setLobby(data);
  },
});
tRPCJoin
Move Fast & Break Nothing. End-to-end typesafe APIs made easy.
5,015Members
Resources
Recent Announcements

Similar Threads

Was this page helpful?

Similar Threads

SSE Subscriptions freeze app when multiple tabs open
MugetsuMMugetsu / ❓-help
6mo ago
Infinite session query when tab is in background
CypherCCypher / ❓-help
3y ago
Subscriptions
Ahmed EidAAhmed Eid / ❓-help
3y ago
Doubled subscriptions in React with useSubscription
Steve ASSteve A / ❓-help
11mo ago