Kamal Nayan
Kamal Nayan

Reputation: 1718

Flow provides null as data from room database

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.

Upvotes: 0

Views: 816

Answers (2)

Jasvir
Jasvir

Reputation: 81

Use collect or first like the code below

connectViewModel.getProfilesFromDB().collect { 
      //do stuff
}

Upvotes: 2

Praveen
Praveen

Reputation: 3486

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
    }

Upvotes: 0

Related Questions