Hello :slightly_smiling_face: Just a quick questio...
# squarelibraries
y
Hello 🙂 Just a quick question about okhttp and cache, one of my client is asking me to add a cache strategy such as: 1. get data and cache it 2. if the data is cached <30 min then just show cache 3. if cache > 30 min && hasInternet try get data and cache but if for some reason the call fail show cache 4. delete all cache which are 1 week old I’ve never seen anything like this done client side, do you guys have any advice to either implement this or maybe some header I don’t know about I’ve setup a small server in localhost to test things out, I’ve added a
Cache-Control: max-age=60;max-stale=120
to test things with OkHttp, the
max-age
prevent calling the server for 60 seconds but the
max-stale
isn’t doing anything or I’m not using it properly
✅ 1
j
The only thing that’s tricky about this is 3, ‘cache if error’. To implement this on the client, make your first HTTP request with no cache-control headers, and then in a catch clause you make a second HTTP request that adds cache-control headers that specify that you’re okay reading a stale value from the cache.
On the server you’ll serve a Cache-Control header that says ‘fresh for 30 minutes’
OkHttp doesn’t have a mechanism to delete things from the cache on a schedule. But you can use cache headers to prevent responses older than 7 days from being returned
y
I’ve tried reading stale value from the cache when offline but I’m getting a
java.net.ConnectException: Failed to connect to /10.0.2.2:8000
while the response should be returned because of the
max-stale=120
j
Add
only-if-cached
to prevent the network call
maybe also add
max-age=120
?
y
Why add
max-age=120
isn’t the 2 other enough to use the cache?