Handling offline and flaky networks

Networking Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Pick the fix

Users on trains see 'No connection' and lose the note they just wrote. Best design?

Options
Hint 1 of 1

Where should the note live until it's uploaded?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A Save the note to Room immediately and enqueue a sync worker with a network constraint

Correct. The note is safe and syncs when the network returns.

Why not the others?
  • B Disable the Save button while offline. Users can't save at all.
  • C Retry the request in a loop until it works. Drains battery and still loses the note if the app is killed.
  • D Check connectivity before saving. Checks are unreliable on trains, and the note is still lost.

30-second answer

Show cached data instead of an error page, mark it as possibly out of date, and queue user changes locally so they sync later with WorkManager and a network constraint. Don't rely on 'is online' checks before requests: a connected network can still fail. Try the request, handle IOException, and react to connectivity changes to retry.

Practise saying it · 35 s. No recording, just a timer

Explain how to handle offline.

Say your answer out loud, then check which of these points you covered:

  • Show cached data
  • Queue writes locally
  • WorkManager with network constraint
  • Don't gate on 'is online'

Deep dive

ConnectivityManager.registerDefaultNetworkCallback reports changes; NET_CAPABILITY_VALIDATED means the network reached the internet.

Metered networks: defer big downloads to unmetered with a WorkManager constraint.

Optimistic updates show the change at once and roll back on failure.

Test with the emulator's network throttling and airplane mode.

Common mistakes

  • Blocking requests based on an 'is online' check.
  • Showing a full-screen error when cached data exists.
  • Losing user edits made offline.

Senior take & follow-ups

Lead with user experience (cached data, queued writes), then the APIs.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why not check connectivity first?

    Show hint

    It can say connected while requests still fail, or the reverse.

  2. How do you sync offline edits?

    Show hint

    Store them locally and enqueue a constrained WorkManager job.

Suggest a fix if something here is wrong or out of date.