I'm trying to upgrade the class SingleLiveEvent.kt from the next article, to the latest libraries for implementation:
STAR-ZERO on Medium -> singleliveevent-livedata-with-multi-observers
Compiler says that the next methods "overrides nothing":
override fun observe(owner: LifecycleOwner, observer: Observer<T>)
override fun removeObserver(observer: Observer<T>)
I'm a bit lost with it, do someone know what changes in the latest versions?
CLASS:
import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean
class SingleLiveEvent<T> : MutableLiveData<T>() {
private val pending = AtomicBoolean(false)
private val observers = mutableSetOf<Observer<T>>()
private val internalObserver = Observer<T> { t ->
if (pending.compareAndSet(true, false)) {
observers.forEach { observer ->
observer.onChanged(t)
}
}
}
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<T>) {
observers.add(observer)
if (!hasObservers()) {
super.observe(owner, internalObserver)
}
}
override fun removeObservers(owner: LifecycleOwner) {
observers.clear()
super.removeObservers(owner)
}
override fun removeObserver(observer: Observer<T>) {
observers.remove(observer)
super.removeObserver(observer)
}
@MainThread
override fun setValue(t: T?) {
pending.set(true)
super.setValue(t)
}
@MainThread
fun call() {
value = null
}
}
CodePudding user response:
That's quite an old article and those methods changed in the meantime. You can either override the proper ones by your self with Code
-> Override Methods...
or just copy them from here:
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, observer)
}
override fun removeObserver(observer: Observer<in T>) {
super.removeObserver(observer)
}
The difference is here: observer: Observer<in T>