Search code examples
cachingrtk-query

When is the cacheEntryRemoved promise fulfilled?


The docs say this:

cacheEntryRemoved - A Promise that allows you to wait for the point in time when the cache entry has been removed from the cache, by not being used/subscribed to any more in the application for too long or by dispatching api.utils.resetApiState.

I've visually scanned the docs and I do not yet understand this part as well as I'd like to.

Does the above quote mean that the promise is fulfilled when the component that uses the query unmounts?

What about when the component is receiving streaming updates?

Is it good practice to partially unsubscribe from an existing WebSockets connection immediately after the cacheEntryRemoved promise is fulfilled in onCacheEntryAdded, when a part of the messages being received from the WS server are not needed anymore? Or is it better to unsubscribe in a useEffect hook's cleanup function from that channel from the WS connection?

I have a single Socket.IO connection that is used to receive more channels of messages in parallel, some component needs a channel, some other component needs another, some other components need the same channel as an existing mounted component. Is it OK to unsubscribe from a channel after this promise is fulfilled? I have put more information about this in this other question.


Solution

  • It is pretty literal: when the cache entry is removed from the cache.

    For every endpoint-argument-combination, you have one cache entry.

    So, when the first component does a useChatRoomQuery("flower"), a cache entry for that is added (and a onCacheEntryAdded function is run for the "chatroom" entry with the argument "flower"). If another component also uses useChatRoomQuery("flower"), the same cache entry is used (no call to onCacheEntryAdded).
    And if a component calls useChatRoomQuery("afterhour"), that will create a new cache entry (and start another onCacheEntryAdded).

    Once the last component using a cache entry stops using it (by unmounting or changing to another argument), a timer is started (usually, 60 seconds - you can configure this on api and endpoint level via keepUnusedDataFor).
    After that time, the cache entry is removed, and that promise resolves.

    So, generally it is probably a good idea to also unsubscribe from your socket connection - and when this was the last topic you were listening for, also to disconnect from it. After all, nobody was interested in that data for some time and you can always reconnect and add a new listener later.