Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unresolved reference: asLiveData while converting Flow to LiveData

I have the following situation:

There's my repository class:

import com.mikhailovskii.timesapp.util.Result import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flow  class LoginRepository {      fun fetchUser() = flow {         emit(Result.Loading)         delay(1000)         emit(Result.Success((0..20).random()))     }  } 

There's ViewModel class:

import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import com.mikhailovskii.timesapp.util.Result  class LoginViewModel() : ViewModel() {      private val loginRepository = LoginRepository()      private val a = loginRepository.fetchUser()       val user: LiveData<Result<Int>> get() = loginRepository.fetchUser().asLiveData()  } 

And there's Result class:

sealed class Result<out R> {      data class Success<out T>(val data: T) : Result<T>()      object Loading : Result<Nothing>()      object Error : Result<Nothing>()  } 

So, when I try to convert the Repository's Flow to the LiveData with the help of asLiveData method, asLiveData is underlined and studio writes that it's an unresolved reference. But I cannot understand why does it happens, as repository returns Flow. So, how what's the problem and how can I solve it?

like image 209
Sergei Mikhailovskii Avatar asked Apr 24 '20 20:04

Sergei Mikhailovskii


Video Answer


2 Answers

I think you are missing the LiveData dependency.

def lifecycle_version = "2.2.0"  // LiveData implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" 

Documentation

like image 57
MrWeeMan Avatar answered Sep 17 '22 12:09

MrWeeMan


You are missing a dependency:

implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0" 

(or any higher version)

like image 26
CommonsWare Avatar answered Sep 16 '22 12:09

CommonsWare