(240612) Medium Daily Digest

Godomin·2024년 6월 12일

Medium-Daily-Digest

목록 보기
22/24

Kotlin Delegation in Jetpack Compose: A Practical Example

https://medium.com/@jigar.rangani1/kotlin-delegation-in-jetpack-compose-a-practical-example-0ef38bc81e21

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("")

Kotlin’s Explicit Backing Fields: A Cleaner Way to Work with MutableStateFlow

https://noob-programmer.medium.com/kotlins-explicit-backing-fields-a-cleaner-way-to-work-with-mutablestateflow-926e2dbc946e

코틀린 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
}

0개의 댓글