alisahindev
alisahindev

Reputation: 415

How to keep running apollo subscription while capacitor app is on background?

I been developing a react.js chat application which works via websocket connection with apollo-client.It uses capacitor.js to create cross-platform iOS, Android, and Progressive Web Apps with JavaScript, HTML, and CSS. In chat component, a subscription query starts works and listen new for new messages. The problem is that messages are not listening while the app is in the background. New messages starts loaded as soon as open app.I want to make it like whatsapp which load new messages while even app is on background.

Apollo client configuration

const wsLink = process.browser
  ? new SubscriptionClient(WEBSOCKET_URL, {
      reconnect: true,
      connectionParams: () => ({
        headers: {
          authorization: `Bearer ${readLocalStorage('id_token')}`,
          'x-hasura-admin-secret':
            'xxxx',
        },
      }),
    })
  : null;

Component which subscription works

const onSubscriptionData = useCallback(
    ({ subscriptionData: { data } }: OnSubscriptionDataOptions<any>) => {
      if (selectedChatId.current) {
        setMessages([...(data.conversation || {})]);
        markAsRead();
      }
    },
    [selectedChatId.current]
  );

  const { loading: messagesLoading } = useSubscription(MESSAGE_DETAIL_SUBSCRIPTION, {
    onSubscriptionData,
    variables: {
      chat_thread_id: selectedChatId,
      user_id: user_id,
    },
  });

Also capacitor has background plugin

Upvotes: 3

Views: 651

Answers (1)

n00bgramer
n00bgramer

Reputation: 21

I think what you need is Push Notifications (@capacitor/push_notifications).

When a subscription happens in your server (eg. new message) you then send a push notification to your devices. The push notification will be displayed in the device and when you click/open the app you can fetch new data from the server.

Upvotes: 2

Related Questions