From bd98a831ccdf7672d2a1e937e2ea80e6fdd3735f Mon Sep 17 00:00:00 2001 From: Patrick Browne Date: Wed, 8 May 2019 10:01:46 +0200 Subject: [PATCH] feat: Realtime init returns terminate function --- src/lib/realtime.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/lib/realtime.js b/src/lib/realtime.js index 083706901..e031eabaa 100644 --- a/src/lib/realtime.js +++ b/src/lib/realtime.js @@ -5,6 +5,8 @@ const APPS_DOCTYPE = 'io.cozy.apps' /** * Initialize realtime sockets * + * Returns function that closes the realtime and unsubscribe handlers + * * @private * @param {object} * @returns {Promise} @@ -30,13 +32,22 @@ function initializeRealtime({ getApp, onCreate, onDelete, cozyClient }) { } } + let realtime try { - const realtime = new CozyRealtime({ cozyClient }) + realtime = new CozyRealtime({ cozyClient }) realtime.subscribe('created', APPS_DOCTYPE, handleAppCreation) realtime.subscribe('deleted', APPS_DOCTYPE, handleAppRemoval) } catch (error) { console.warn(`Cannot initialize realtime in Cozy-bar: ${error.message}`) } + + return () => { + if (!realtime) { + return + } + realtime.unsubscribe('created', APPS_DOCTYPE, handleAppCreation) + realtime.unsubscribe('deleted', APPS_DOCTYPE, handleAppRemoval) + } } export default initializeRealtime