SingleLiveEvent atomic variable not required
Hi,
I have a question regarding the SingleLiveEvent class, internally It uses an atomic boolean, but it is accessed always in the main thread. It is really required an atomic variable?
Is AtomicBoolean really necessary? Short Answer: Yes, it's justified — but only if multithreading is a real concern. In typical use (main thread only), a regular Boolean would suffice.
Detailed Explanation The original SingleLiveEvent looks like: private val pending = AtomicBoolean(false)
override fun observe(...) { super.observe(...)
if (pending.compareAndSet(true, false)) {
observer.onChanged(t)
}
}
override fun setValue(t: T?) { pending.set(true) super.setValue(t) } This logic ensures that each event is emitted only once, even if configuration changes cause observers to re-subscribe.
Why AtomicBoolean was used: It was originally written to be thread-safe — in case setValue() is called from a background thread, and the observer is on the main thread.
compareAndSet() is atomic and avoids race conditions.
However, in practice: LiveData is intended to be used on the main thread.
In most apps, you only call setValue() or observe() on the UI thread.
If you call postValue(), LiveData switches to the main thread internally.
So, if your project ensures everything is on the main thread, you could safely replace AtomicBoolean with a Boolean.
Possible Optimized Version (Main Thread Only)
private var pending = false
override fun observe(...) { super.observe(...)
if (pending) {
pending = false
observer.onChanged(t)
}
}
override fun setValue(t: T?) { pending = true super.setValue(t) } But you must guarantee:
All setValue() calls are from the main thread.
You never use postValue() (which may post from a background thread).
Recommendation If your app strictly uses LiveData on the main thread, removing AtomicBoolean is fine and more performant.
If there’s any doubt about cross-thread usage (e.g., using postValue()), keep AtomicBoolean for safety.