by lazy

이창민·2022년 2월 7일
0

by lazy

class MyViewModel : ViewModel() {
    private val users: MutableLiveData<List<User>> by lazy {
        MutableLiveData<List<User>>().also {
            loadUsers()
        }
    }

    fun getUsers(): LiveData<List<User>> {
        return users
    }

    private fun loadUsers() {
        // Do an asynchronous operation to fetch users.
    }
}

users를 보면 by를 lazy와 사용한다.
by lazy를 사용할 경우 아래의 코드의 결과는

val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}

fun main() {
    println(lazyValue)
    println(lazyValue)
}

computed
Hello
Hello
가 된다.
lazyValue가 클래스 내부에 포함된 객체라 가정할 경우
class가 생성될 경우 함께 초기화되지 않음
lazyValue가 초기화되는 시점은 최초에 초기화되는 시점이다.
즉, main 함수에서 처음 println(lazyValue) 를 호출할 때, 위의 lazyValue 블록이 실행되고 println(computed)가 실행되고 lazyValue에 Hello가 할당된다.

lazy 프로퍼티는 최초에 생성된 그 값을 계속 재사용하는 프로퍼티이다.
초기화 비용이 많이드는 연산이지만, 이를 계속 재사용해도 되는 경우에 적합하다.

참고자료

https://kotlinlang.org/docs/delegated-properties.html

profile
android 를 공부해보아요

0개의 댓글