0

When I use Flow ( kotlinx.coroutines.flow.Flow) I get null as response. Dao code below :

   @Query("SELECT * FROM connect")
   fun getProfiles(): Flow<List<ConnectModel>>

But when I use List<ConnectModel> and remove flow I get expected result.

My connectImpl code:

 override fun getProfilesFromDB(): LiveData<List<ConnectModel>>
{
    val result = connectDAO.getProfiles()
    return result.asLiveData() 
}

In viewmodel

     private val _users = MutableLiveData<List<ConnectModel>>()
     val users: LiveData<List<ConnectModel>>
    get() = _users


 fun getConnectUsers() {

    viewModelScope.launch {
        val response = getConnectUsersFromDbUseCase.invoke()
        _users.postValue(response.value)

    }
}

If I make the _users lateinit then it works fine but not when it is MutableLiveData.

In Fragment

  viewModel.users.observe(viewLifecycleOwner,{list ->
        if (list != null) {
            for(profile in list)
                Timber.i("Observer Active ${profile.name}")
        }
    })

Databaseenter image description here Any kind of help is appreciated. Thanks in advance.

Kamal Nayan
  • 1,635
  • 1
  • 5
  • 19

2 Answers2

1

Use collect or first like the code below

connectViewModel.getProfilesFromDB().collect { 
      //do stuff
}
Jasvir
  • 71
  • 6
0

There is nothing wrong in your code, I've tried it and it's working perfectly fine as it should. It may be how you are observing this live data after getting it. I've this method in my view model and this is how I'm observing it inside fragment.

    connectViewModel.getProfilesFromDB().observe(viewLifecycleOwner){ 
          //do stuff
    }
Praveen
  • 3,186
  • 2
  • 8
  • 23
  • I need to get the value in viewModel and set the value to a LiveData variable Observe in fragment . And I have updated the question with more code, kindly have a look – Kamal Nayan May 11 '21 at 13:37
  • What is this ```getConnectUsersFromDbUseCase.invoke()``` returning? – Praveen May 11 '21 at 18:14