November 04, 2021
Data를 다루는 LiveData객체를 활용해 이벤트 발생을 처리하는 방법.
class ExampleViewModel: ViewModel() {
private var _event: MutableLiveData<Unit> = MutableLiveData()
val event: LiveData<Unit> = _event
fun callEvent() {
_event.setValue(Unit)
}
}
class ExampleActivity: Activity() {
fun main() {
button.ClickListener {
viewModel.callEvent()
}
viewModel.event.observe {
showClickCount()
}
}
}
class SingleLiveEvent<T> : MutableLiveData<T>() {
private val pending = AtomicBoolean(false)
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
// Observe the internal MutableLiveData
super.observe(owner, Observer<T> { t ->
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
})
}
@MainThread
override fun setValue(t: T?) {
pending.set(true)
super.setValue(t)
}
@MainThread
fun call() {
value = null
}
}
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
fun peekContent(): T = content
}