Changed commited changes load block to avoid changing the state to loading when is not necessary

This commit is contained in:
Abdelilah El Aissaoui 2022-05-23 19:36:06 +02:00
parent 46cb205739
commit 543545d93d
2 changed files with 36 additions and 5 deletions

View File

@ -0,0 +1,26 @@
package app.extensions
import kotlinx.coroutines.*
/**
* Calls a code [onDelayTriggered] if [block] has not completed before the time specified in [delayMs].
* Use case: Sometimes is not worth updating the UI with a state to "loading" if the load code executed afterwards is really
* fast.
*/
suspend fun delayedStateChange(delayMs: Long, onDelayTriggered: suspend () -> Unit, block: suspend () -> Unit) {
val scope = CoroutineScope(Dispatchers.IO)
var completed = false
scope.launch {
delay(delayMs)
if(!completed) {
onDelayTriggered()
}
}
try {
block()
scope.cancel()
} finally {
completed = true
}
}

View File

@ -1,5 +1,6 @@
package app.viewmodels
import app.extensions.delayedStateChange
import app.git.DiffManager
import app.git.RefreshType
import app.git.TabState
@ -9,6 +10,8 @@ import org.eclipse.jgit.diff.DiffEntry
import org.eclipse.jgit.revwalk.RevCommit
import javax.inject.Inject
private const val MIN_TIME_IN_MS_TO_SHOW_LOAD = 300L
class CommitChangesViewModel @Inject constructor(
private val tabState: TabState,
private val diffManager: DiffManager,
@ -19,15 +22,17 @@ class CommitChangesViewModel @Inject constructor(
fun loadChanges(commit: RevCommit) = tabState.runOperation(
refreshType = RefreshType.NONE,
) { git ->
_commitChangesStatus.value = CommitChangesStatus.Loading
delayedStateChange(
delayMs = MIN_TIME_IN_MS_TO_SHOW_LOAD,
onDelayTriggered = { _commitChangesStatus.value = CommitChangesStatus.Loading }
) {
val changes = diffManager.commitDiffEntries(git, commit)
val changes = diffManager.commitDiffEntries(git, commit)
_commitChangesStatus.value = CommitChangesStatus.Loaded(commit, changes)
_commitChangesStatus.value = CommitChangesStatus.Loaded(commit, changes)
}
}
}
sealed class CommitChangesStatus {
object Loading : CommitChangesStatus()
data class Loaded(val commit: RevCommit, val changes: List<DiffEntry>) : CommitChangesStatus()