2

ニュース アプリを開発していますが、MainViewModel.kt クラスで次のエラーが発生します。型の不一致: 推論された型はリスト以外ですか? 期待されていた

My MainViewModel.kt の下

class MainViewModel(
    private val sportNewsInterface: SportNewsInterface

) : ViewModel(), CoroutineScope {
    // Coroutine's background job
    private val job = Job()
    // Define default thread for Coroutine as Main and add job
    override val coroutineContext: CoroutineContext = Dispatchers.Main + job

    private val showLoading = MutableLiveData<Boolean>()
    private val sportList = MutableLiveData <List<SportNewsResponse>>()
    val showError = SingleLiveEvent<String>()

    fun loadNews() {
        // Show progressBar during the operation on the MAIN (default) thread
        showLoading.value = true
        // launch the Coroutine
        launch {
            // Switching from MAIN to IO thread for API operation
            // Update our data list with the new one from API
            val result = withContext(Dispatchers.IO) { sportNewsInterface.getNews()
            }
            // Hide progressBar once the operation is done on the MAIN (default) thread
            showLoading.value = false
            when (result) {


                is UseCaseResult.Success<*> -> {
                    sportList.value = result.data
                }
                is UseCaseResult.Error -> showError.value = result.exception.message
                 }
                }
            }



    override fun onCleared() {
        super.onCleared()
        // Clear our job when the linked activity is destroyed to avoid memory leaks
        job.cancel()
    }
}

以下 UserCaseResult.kt

sealed class UseCaseResult<out T : Any> {
    class Success<out T : Any>(val data: T) : UseCaseResult<List<SportNewsResponse>>()

    class Error(val exception: Throwable) : UseCaseResult<Nothing>()
}
4

2 に答える 2

4

同じ問題が発生したため、ビルドをクリアしてからもう一度ビルドすると、機能しました。

于 2021-01-09T16:28:04.283 に答える