العبد
العبد

Reputation: 397

Sealed class in Kotlin, Incompatible types error cannot return parent type

I have this sealed class represent the view state

sealed class ViewState<out ResultType>(
) {
    data class Success<ResultType>(val data: ResultType?) : ViewState<ResultType>()
    data class Error(val message: String) : ViewState<Nothing>()
    object Loading : ViewState<Nothing>()

}

here I use viewState

fun <T, A> performGetOperation(databaseQuery: () -> LiveData<T>)): LiveData<ViewState<T>> =
        liveData(Dispatchers.IO) {
        emit(ViewState.Loading)
        val cache: LiveData<ViewState.Success<T>> = databaseQuery.invoke()
                    .map { ViewState.Success<T>(it) }

        emitSource(cache)
        }

this line is crazy emitSource(cache) give me emitSource(cache)

Required:
LiveData<ViewState<T>>
Found:
LiveData<ViewState.Success<T>>

Upvotes: 2

Views: 845

Answers (1)

ChristianB
ChristianB

Reputation: 2690

It was a simple type definition problem. You defined cache as LiveData<ViewState.Success<T>> which does not match the returning type of LiveData<ViewState<T>>.

You have to change the type from val cache: LiveData<ViewState.Success<T>> to val cache: LiveData<ViewState<T>>.

Here is the correct functions:

fun <T, A> performGetOperation(databaseQuery: () -> LiveData<T>)): LiveData<ViewState<T>> = liveData(Dispatchers.IO) {
  emit(ViewState.Loading)
  
  val cache: LiveData<ViewState<T>> = databaseQuery.invoke()
                    .map { ViewState.Success<T>(it) }

  emitSource(cache)
}

Upvotes: 4

Related Questions