Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SingleLiveEvent issue after migration to AndroidX

After migration to AndroidX by using Android studio 3.2.1 I cannot run app due to this error:

SingleLiveEvent.java:29: error: name clash: observe(LifecycleOwner,Observer<T#1>) in SingleLiveEvent and observe(LifecycleOwner,Observer<? super T#2>) in LiveData have the same erasure, yet neither overrides the other
    public void observe(LifecycleOwner owner, final Observer<T> observer) {
                ^
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in class SingleLiveEvent
    T#2 extends Object declared in class LiveData
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

I googled it, and found solutions for other things, but how to solve this elegantly? I don't want to refactor whole app in every place I use single live event.

like image 703
vanste25 Avatar asked Dec 11 '18 00:12

vanste25


People also ask

What is SingleLiveEvent?

SingleLiveEvent:- SingleLiveEvent is a subclass of MutableLiveData with a single Observer Observing it at a time, hence it is aware of view's lifecycle.

What does migrate to AndroidX?

AndroidX replaces the original support library APIs with packages in the androidx namespace. Only the package and Maven artifact names changed; class, method, and field names did not change. Caution: As of late 2021, most of the library ecosystem already supports AndroidX natively.

How do you observe live data in activity?

Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.


1 Answers

I have found the issue. LiveData provides this:

public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer)

while SingleLiveEvent provides:

public void observe(LifecycleOwner owner, final Observer<T> observer)

The solution is to change the method signature in SingleLiveEvent to match LiveData

like image 173
vanste25 Avatar answered Sep 26 '22 06:09

vanste25