SharedPreference처럼 컴포즈의 remember에서도 delegation을 사용할 수 있다.
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class ComposeStateDelegate<T>(initialValue: T) : ReadWriteProperty<Any?, T> {
private var state = mutableStateOf(initialValue)
override fun getValue(thisRef: Any?, property: KProperty<*>): T = state.value
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
state.value = value
}
}
@Composable
fun <T> rememberState(initialValue: T): ComposeStateDelegate<T> {
return remember { ComposeStateDelegate(initialValue) }
}
그러면 아래와 같이 더 간단하게 쓸 수 있다.
var name by rememberState("")
코틀린 2.0에서 Explicit Backing Fields가 소개되었다.
https://github.com/Kotlin/KEEP/blob/explicit-backing-fields-re/proposals/explicit-backing-fields.md
class SomeViewModel : ViewModel() {
private val _city = MutableStateFlow("")
val city: StateFlow<String> get() = _city
}
field에 대한 접근 제한자는 private가 되기 때문에 외부에는 StateFlow로 보인다.
val city: StateFlow<String>
field = MutableStateFlow("")
fun updateCity(newCity: String) {
city.value = newCity // visible as MutableStateFlow, calling field
}