Skip to content

Instantly share code, notes, and snippets.

@AfzalivE
Last active Aug 18, 2020
Embed
What would you like to do?
Syncing two local and remote db tables
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
}
}
}
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()
)
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