Strategy to sync offline local data with REST API after resuming connection
Asked Answered
K

2

7

I have a hybrid application that is available on android and through browsers. Both clients use the REST API and websockets. Data is stored in localStorage. I would like the mobile devices to be able to modify offline resources, and after connecting to the Internet the data was synchronized with the API.

How to make such a comparison of data after connecting to the Internet and get the right version?

Problem scenario:

  1. User has a list of notes fetched from the API on the phone.
  2. User turns off the Internet
  3. User remains logged in with the JWT token. Modifies a note, deletes another note, adds a new one or does anything else with the notes
  4. User turns on the Internet.
  5. What should happen here?

My ideas on how to solve this problem:

  • creating a synchronization endpoint and comparing collections by updated_at column when connection is received.
  • compare objects for difference with this utility
Kelly answered 11/4, 2020 at 10:57 Comment(0)
G
6

Depending on your ambitions for the app, you may want to implement a proper sync mechanism able to handle more than a list of notes.

Easy way: go piggy backing on the update date, you can compare edition dates and decide that last write wins.

Hard way: I would recommend you to have a look at CRDTs. These kind of data structures ensure that the state will be eventually consistent, making it a perfect fit for your need. Many implementations exist it depends on your toolchain, for instance Logux provides some CRDTs for javascript.

You can also rely on databases thought for data sync and conflict resuolution like https://couchdb.apache.org//https://pouchdb.com/. Also https://riak.com/products/riak-kv/riak-distributed-data-types/index.html?p=10947.html offer CRDTs support.

If you want to dig on merging text data I suggest you to look at Diff-Match-Patch algorithm developed by Google for their Docs apps, many ports are available.

Beware implementing real offline and synchronisation capabilities for apps is far from being trivial.

Godding answered 11/5, 2020 at 12:32 Comment(0)
T
1

I have found a tutorial for making offline first mobile application that discusses some of the best practices for making offline app with sync facility. Please refer below link for the tutorial let me know if it helps.

How to Make Your App Available Offline

Tecu answered 11/5, 2020 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.