Last active
August 18, 2020 04:39
-
-
Save AfzalivE/48a9e225246c5cee144b06695f68731a to your computer and use it in GitHub Desktop.
Syncing two local and remote db tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test | |
class DatabaseSyncer() { | |
// Updated thanks to @gildor | |
private fun findUpdatedNotes( | |
allLocalNotes: List<Note>, | |
allRemoteNotes: List<Note> | |
): List<Note> { | |
val newLocalNotes = allLocalNotes.minus(allRemoteNotes).associateBy(Note::id) | |
val newRemoteNotes = allRemoteNotes.minus(allLocalNotes) | |
val updatedNotes = newRemoteNotes.map { remoteNote -> | |
val localNote = newLocalNotes[remoteNote.id] | |
when { | |
localNote == null -> remoteNote | |
remoteNote.creationId == localNote.creationId -> newestNote(localNote, remoteNote) | |
else -> remoteNote.copy(id = 0) | |
} | |
}.sortedByDescending { | |
// we add copied notes at the end to avoid auto-incremented ID | |
// from being the same as later non-conflicting notes | |
it.id | |
} | |
return updatedNotes | |
} | |
private fun newestNote(note1: Note, note2: Note): Note { | |
return if (note1.updatedAt.isAfter(note2.updatedAt)) { | |
note1 | |
} else { | |
note2 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test | |
data class Note( | |
val id: Long = 0, | |
val title: String, | |
val creationId: String = UUID.randomUUID().toString(), | |
val createdAt: OffsetDateTime = OffsetDateTime.now(), | |
val updatedAt: OffsetDateTime = OffsetDateTime.now() | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
localNotes has 1 new note, remoteDb has 2 new notes | |
localNotes has 2 new notes and remoteDb has 1 new note | |
localNotes has new notes, remoteDb has no notes at all | |
localNotes has no new notes, remoteDb has new notes | |
localNotes has no notes at all and remoteDb has new notes | |
localNotes and remoteDb have modified the same note, localDb modified last | |
localNotes has new notes, remoteDb has new notes | |
localNotes has new notes, remoteDb has no new notes | |
localNotes and remoteDb have modified the same note, remoteDb modified last |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment