-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHistoryViewModel.kt
43 lines (35 loc) · 1.11 KB
/
HistoryViewModel.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package no.nilsen.compose.common
import androidx.databinding.ObservableBoolean
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
abstract class HistoryViewModel<T> : ViewModel() {
abstract val initialState: T
var history: MutableList<T> = mutableListOf() // todo use snapshotFlow?
var index: Int = 0
val stateFlow by lazy {
history.add(initialState)
MutableStateFlow<T>(initialState)
}
protected fun setState(newState: T) {
stateFlow.value = newState
history = (history.take(index + 1) + newState).toMutableList()
index++
updateBackForward()
}
fun updateBackForward() {
canGoForward.set(index < history.size - 1)
canGoBack.set(index > 0)
}
val canGoForward = ObservableBoolean()
val canGoBack = ObservableBoolean()
fun goForward() {
if (!canGoForward.get()) return
stateFlow.value = history[++index]
updateBackForward()
}
fun goBack() {
if (!canGoBack.get()) return
stateFlow.value = history[--index]
updateBackForward()
}
}