본문 바로가기
Java & Kotlin/Kotlin

observable, vetoable를 통한 프로퍼티 변경 감지

by devson 2021. 11. 6.

Kotlin은 Delegates를 통해 프로퍼티의 변경을 감지할 수 있는 매우 편리한 기능을 제공한다.

 

observable

Delegates.observable은 단순하게 프로퍼티가 변경됨을 감지하는 역할을 한다.

import kotlin.properties.Delegates
fun main() {
var watchedNumber by Delegates.observable(0) { property, oldValue, newValue ->
println("`${property.name}` changed from `$oldValue` to `$newValue`")
}
watchedNumber = 1
watchedNumber = 2
watchedNumber = 3
}

 

위 코드를 실행 시키면 콘솔에 아래와 같이 출력이 된다.

 

vetoable

먼저 veto 라는 단어는 거부 라는 뜻이다.

Delegates.vetoable은 값이 변경 됨을 감지하여 변경을 할 것인지 말 것인지를 지정할 수 있다.

 

예로, 특정 프로퍼티에 대해 항상 값이 증가해야만 한다고 했을 때 아래와 같이 vetoable을 활용할 수 있다.

import kotlin.properties.Delegates
fun main() {
var increasingNumber by Delegates.vetoable(0) { property, oldValue, newValue ->
println("`${property.name}` is tried to be changed from `$oldValue` to `$newValue`")
oldValue < newValue
}
increasingNumber = 1
println(increasingNumber) // 1
increasingNumber = 5
println(increasingNumber) // 5
increasingNumber = 3
println(increasingNumber) // 5
}

 

위 코드를 실행 시키면 콘솔에 아래와 같이 출력이 된다.

댓글