Skip to content

Commit

Permalink
Fix synchronization issues after offline period
Browse files Browse the repository at this point in the history
  • Loading branch information
profiluefter committed Apr 20, 2021
1 parent 7e2902a commit eb0f739
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,18 @@ class NotesRepository @Inject constructor(
suspend fun deleteNote(note: Note) {
val rawNote = local.todoDao().getByLocalID(note.localID)

if(rawNote.id == "NEW") {
local.todoDao().delete(rawNote)
return
}

if (isNetworkAvailable()) {
local.todoDao().delete(rawNote)
try {
remote.deleteTodo(rawNote.id.toInt(), username, password)
} catch (e: Exception) {
local.todoDao().insert(rawNote)
local.todoDao().scheduleDelete(note.localID)
throw RuntimeException("Error while deleting note $note from server", e)
}
} else
Expand Down Expand Up @@ -96,6 +102,11 @@ class NotesRepository @Inject constructor(
}

suspend fun synchronize() {
if(!isNetworkAvailable()) {
Log.w(logTag, "Synchronization ignored since the device is offline")
return
}

Log.i(logTag, "Starting synchronization...")
synchronizeLists()
Log.i(logTag, "Finished list synchronization! Starting todo synchronization...")
Expand All @@ -114,13 +125,15 @@ class NotesRepository @Inject constructor(
Log.d(logTag, "Deleting ${deleteLists.size} todo lists")
deleteLists.forEach {
remote.deleteList(it.id.toInt(), username, password)
local.listDao().delete(it)
}

val uploadLists = remainingLocal.filter { it.id == "NEW" }
Log.d(logTag, "Uploading ${uploadLists.size} todo lists")
uploadLists.forEach {
val (_, newID) = remote.newList(it, username, password)
local.listDao().changeID(it.localID, newID)
local.todoDao().changeListID(it.localID, newID)
}

val remainingLists = local.listDao().getAll()
Expand Down Expand Up @@ -173,6 +186,7 @@ class NotesRepository @Inject constructor(
Log.d(logTag, "Deleting ${deleteTodos.size} todos")
deleteTodos.forEach {
remote.deleteTodo(it.id.toInt(), username, password)
local.todoDao().delete(it)
}

val uploadTodos = remainingLocal.filter { it.id == "NEW" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ interface TodoDao {
@Query("UPDATE rawtodo SET id = :id WHERE localID = :localID")
suspend fun changeID(localID: Int, id: String)

@Query("UPDATE rawtodo SET todoListId = :remoteID WHERE localListID = :localID")
suspend fun changeListID(localID: Int, remoteID: String)

@Delete
suspend fun delete(rawTodo: RawTodo)

Expand Down

0 comments on commit eb0f739

Please sign in to comment.