androidkotlingraphqlapollo-android

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

  • 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