Last active
September 7, 2022 11:09
-
-
Save qwert2603/23201695451c987dd3721d9f25137f7e to your computer and use it in GitHub Desktop.
ViewModelStateFlow
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
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 | |
} | |
} |
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
class SomeFragment { | |
private val vm = SomeViewModel() | |
fun onCreate() { | |
val currentValue: Int = vm.flow.value | |
// vm.flow.setValue(4) // compilation error | |
} | |
} |
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
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