Created
February 7, 2022 14:50
-
-
Save Dr-TSNG/186e407525cef1ea60789eb2fc144e41 to your computer and use it in GitHub Desktop.
Multiple delegate state with Jetpack Compose
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
package icu.nullptr.util.compose | |
import androidx.compose.runtime.getValue | |
import androidx.compose.runtime.mutableStateOf | |
import androidx.compose.runtime.setValue | |
import kotlin.reflect.KProperty | |
class DelegateState<T>(initial: T, private val sideEffectSetter: (T) -> Unit) { | |
private var snapshot by mutableStateOf(initial) | |
var value: T | |
get() = snapshot | |
set(value) { | |
snapshot = value | |
sideEffectSetter(snapshot) | |
} | |
operator fun component1(): T = value | |
operator fun component2(): (T) -> Unit = { value = it } | |
} | |
fun <T> delegateStateOf(initial: T, sideEffectSetter: (T) -> Unit) = DelegateState(initial, sideEffectSetter) | |
@Suppress("NOTHING_TO_INLINE") | |
inline operator fun <T> DelegateState<T>.getValue(thisObj: Any?, property: KProperty<*>): T = value | |
@Suppress("NOTHING_TO_INLINE") | |
inline operator fun <T> DelegateState<T>.setValue(thisObj: Any?, property: KProperty<*>, value: T) { | |
this.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
... | |
import icu.nullptr.util.compose.delegateStateOf | |
import icu.nullptr.util.compose.getValue | |
import icu.nullptr.util.compose.setValue | |
class ExampleViewModel : ViewModel() { | |
var darkThemePreference by | |
delegateStateOf(MyApplication.pref.getInt("dark_theme", FOLLOW_SYSTEM)) { | |
MyApplication.pref.edit().putInt("dark_theme", it).apply() | |
} | |
} | |
// When darkThemePreference change, related composables will automatically recompose | |
@Composable | |
fun Example() { | |
val viewModel = viewModel<ExampleViewModel>() | |
ThemeButton( | |
isDarkTheme = viewModel.darkThemePreference, | |
onChange = { viewModel.darkThemePreference = it } | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment