Skip to content

Instantly share code, notes, and snippets.

@Dr-TSNG
Created February 7, 2022 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dr-TSNG/186e407525cef1ea60789eb2fc144e41 to your computer and use it in GitHub Desktop.
Save Dr-TSNG/186e407525cef1ea60789eb2fc144e41 to your computer and use it in GitHub Desktop.
Multiple delegate state with Jetpack Compose
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
}
...
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