Skip to content

Instantly share code, notes, and snippets.

Avatar

Fabio Collini fabioCollini

View GitHub Profile
View ViewModelTest.kt
@Test
fun `sets the result when an input changes`() {
Snapshot.withMutableSnapshot {
viewModel.v1 = "10"
viewModel.v2 = "20"
}
assertThat(viewModel.result).isEqualTo("30")
}
View ViewModelTest.kt
class ViewModelTest {
@get:Rule
val mainCoroutineRule = MainCoroutineRule()
private val viewModel by lazy {
CalculatorViewModel(SavedStateHandle(mutableMapOf()))
}
@Test
fun `sets the result when an input changes`() {
View CalculatorViewModel.kt
class CalculatorViewModel(
state: SavedStateHandle,
) : ViewModel() {
var v1 by state.mutableStateOf("0")
var v2 by state.mutableStateOf("0")
val result by state.mutableStateOf("0") { valueLoadedFromState, setter ->
snapshotFlow { v1 to v2 }
.drop(if (valueLoadedFromState != null) 1 else 0)
.mapLatest {
View mutableStateOf.kt
fun <T> SavedStateHandle.mutableStateOf(
defaultValue: T,
initializer: (valueLoadedFromState: T?, setter: (T) -> Unit) -> Unit = { _, _ -> },
) = PropertyDelegateProvider<Any, SavedStateHandleDelegate<T>> { _, property ->
SavedStateHandleDelegate(
savedStateHandle = this,
key = property.name,
defaultValue = defaultValue,
initializer = initializer
)
View SavedStateHandleDelegate.kt
class SavedStateHandleDelegate<T>(
private val savedStateHandle: SavedStateHandle,
private val key: String,
defaultValue: T,
initializer: (valueLoadedFromState: T?, setter: (T) -> Unit) -> Unit
) : ReadWriteProperty<Any, T> {
private val state: MutableState<T>
init {
val savedValue = savedStateHandle.get<T>(key)
View CalculatorViewModel.kt
class CalculatorViewModel(
state: SavedStateHandle,
) : ViewModel() {
var v1 by state.mutableStateOf("0")
var v2 by state.mutableStateOf("0")
var result by state.mutableStateOf("0")
private set
init {
View mutableStateOf.kt
fun <T> SavedStateHandle.mutableStateOf(
defaultValue: T,
) = PropertyDelegateProvider<Any, SavedStateHandleDelegate<T>> { _, property ->
SavedStateHandleDelegate(
savedStateHandle = this,
key = property.name,
defaultValue = defaultValue,
)
}
View SavedStateHandleDelegate.kt
class SavedStateHandleDelegate<T>(
private val savedStateHandle: SavedStateHandle,
private val key: String,
defaultValue: T,
) : ReadWriteProperty<Any, T> {
private val state: MutableState<T>
init {
val savedValue = savedStateHandle.get<T>(key)
state = mutableStateOf(
View Calculator.kt
@Composable
fun Calculator(state: CalculatorViewModel) {
Column {
TextField(value = state.v1, onValueChange = { state.v1 = it })
TextField(value = state.v2, onValueChange = { state.v2 = it })
Text(text = state.result)
}
}
View CalculatorViewModel.kt
class CalculatorViewModel : ViewModel() {
var v1 by mutableStateOf("0")
var v2 by mutableStateOf("0")
var result by mutableStateOf("0")
private set
init {
snapshotFlow { v1 to v2 }
.mapLatest {
sum(it.first, it.second)