'How to invalidate apollo android cache?

Here is my apollo client code for caching

val apolloSqlHelper = ApolloSqlHelper.create(context,"my_app")
        val sqlNormalizedCacheFactory = SqlNormalizedCacheFactory(apolloSqlHelper)
        val cacheKeyResolver = object: CacheKeyResolver(){
            override fun fromFieldRecordSet(
                field: ResponseField,
                recordSet: MutableMap<String, Any>
            ): CacheKey {
                return if (recordSet["__typename"] == "Repository") {
                    CacheKey.from(recordSet["id"] as String)
                } else {
                    CacheKey.NO_KEY
                }
            }

            override fun fromFieldArguments(
                field: ResponseField,
                variables: Operation.Variables
            ): CacheKey {
                return  CacheKey.NO_KEY
            }
        }

        ApolloClient.builder().serverUrl(baseUrl)
            .normalizedCache(sqlNormalizedCacheFactory,cacheKeyResolver)
            .okHttpClient(okHttpClient).build()

I am doing a query after which apollo caches my results but when more data is added to the query I am not understand how to invalidate the cache depending on whether results have changed or not. If no results changed get data from cache or fetch new data and update the cache



Solution 1:[1]

I don't need to manually invalidate the cache. Apollo Android handles it for me

This code worked for me

apolloClient.query(MyQuery()).responseFetcher(ApolloResponseFetchers.NETWORK_FIRST)

ApolloResponseFetchers also provide various options like CACHE_FIRST,CACHE_ONLY etc

Solution 2:[2]

First option is using a specific ResponseFetcher on your query to adjust your cache strategy:

val query = someQuery.toBuilder()
    .responseFetcher(ApolloResponseFetchers.NETWORK_ONLY)
    .build()

apolloClient.query(query)

However if you need to invalidate cache for some specific cache key you may go ahead and use ApolloStore.

apolloClient.apolloStore.remove(yourCacheKey)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pritish
Solution 2 Konstantin Levitskiy