toteto
toteto

Reputation: 11

Kotlin type missmatch. Expected Any received MyObject

I am making a list of observable LiveData objects, that should contain Resource object (https://developer.android.com/topic/libraries/architecture/guide.html#addendum). I don't care what type of data that Resource object is containing.

abstract class LiveResources : LiveData<Resource<Any>>() {
  private val mediatorLiveData = MediatorLiveData<Resource<Any>>()
  protected val resources = HashSet<LiveData<Resource<Any>>>()

  fun addResource(source: LiveData<Resource<Any>>) {
    resources.add(source)
    mediatorLiveData.addSource(source, resourceObserver)
  }

  fun removeResource(source: LiveData<Resource<Any>>) {
    resources.remove(source)
    mediatorLiveData.removeSource(source)
  }

  private val resourceObserver = Observer<Resource<Any>> {
    onSourceChange()
  }

  abstract fun onSourceChange()
}

Unfortunately when I try to use LiveResources.addResource() with LiveData<Resource<List<String>>> I get TypeMismatch error in my IDE, saying that LiveData<Resource<Any>> was expected.

Upvotes: 1

Views: 1070

Answers (3)

Nikola Despotoski
Nikola Despotoski

Reputation: 50548

You should generify the classes to accept Resource<T> i.e LiveData<Resource<T>>. Any is the covariance of any object passed, but I think you are not trying to achieve that.

Another friendly advice is that you don't need to add another abstraction on top of MediatorLiveData that solely does the same you have implemented.

Upvotes: 0

Splash
Splash

Reputation: 1340

Haven't tried it, but I think this would work

fun <T:Any> addResource(source: LiveData<Resource<T>>)

Upvotes: 1

Alex
Alex

Reputation: 7926

Your Resource (and/or LiveData) class should be defined with generic covariance in order to make it work. Like so:

class Resource<out T> // <- out marks generic type as covariant

Upvotes: 1

Related Questions