How to invalidate apollo android cache?

740 Views Asked by At

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

2

There are 2 best solutions below

0
BraveEvidence On BEST ANSWER

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

0
Konstantin Levitskiy On

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)