Skip to content

Instantly share code, notes, and snippets.

@belinwu
Forked from qwert2603/BaseViewModel.kt
Created September 7, 2022 11:09
Show Gist options
  • Save belinwu/cd669028fe5c2ebd5473af1b4c6a5929 to your computer and use it in GitHub Desktop.
Save belinwu/cd669028fe5c2ebd5473af1b4c6a5929 to your computer and use it in GitHub Desktop.
ViewModelStateFlow
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
sealed class ViewModelStateFlow<T>(stateFlow: StateFlow<T>) : StateFlow<T> by stateFlow
private class ViewModelStateFlowImpl<T>(
initial: T,
val wrapped: MutableStateFlow<T> = MutableStateFlow(initial)
) : ViewModelStateFlow<T>(wrapped)
abstract class BaseViewModel : ViewModel() {
protected fun <T> createViewModelStateFlow(initial: T): ViewModelStateFlow<T> =
ViewModelStateFlowImpl(initial)
protected fun <T> ViewModelStateFlow<T>.setValue(value: T): Unit = when (this) {
is ViewModelStateFlowImpl -> wrapped.value = value
}
}
class SomeFragment {
private val vm = SomeViewModel()
fun onCreate() {
val currentValue: Int = vm.flow.value
// vm.flow.setValue(4) // compilation error
}
}
import kotlinx.coroutines.delay
class SomeViewModel : BaseViewModel() {
val flow = createViewModelStateFlow(0)
suspend fun load() {
flow.setValue(1)
delay(1000)
flow.setValue(flow.value + 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment