Question: when refactoring to use the LiveData Bui...
# android
n
Question: when refactoring to use the LiveData Builder, I'm getting an unwanted database read whenever the screen rotates. Here is the code: Unwanted Read:
Copy code
SomeViewModel: ViewModel(), LifecycleObserver {

   init {
       viewModelScope.launch { databaseStuff() }
   }

   suspend fun databaseStuff() =
       liveData {
           emit(ViewState.Loading)
           emit(retrieveDataUseCase.getDatabaseStuff().fold({
               ViewState.Error
           }, {
               if (it.retrievedFromDatabase) {
                   ViewState.ReadFromDatabase(it)
               } else {
                   ViewState.SuccessfulFetch(it)
               }
           }))
       }
   }
}

SomeFragment: Fragment() {
   viewLifecycleOwner.lifecycleScope.launchWhenCreated {
       viewModel.databaseStuff().observe(viewLifecycleOwner, {
           renderState(it)
       })
   }
}
Correct behavior:
Copy code
SomeOtherViewModel: ViewModel(), LifecycleObserver {
   init {
       viewModelScope.launch { databaseStuff() }
   }

   val myLiveData: LiveData<Item>
       get() = _myLiveData
   private val _myLiveData = MutableLiveData<Item>()

   @ExperimentalCoroutinesApi
   suspend fun databaseStuff() =
       retrieveDataUseCase.itemFlow().collect {
           _myLiveData.value = it
       }
   }
}

SomeOtherFragment: Fragment() {
   viewLifecycleOwner.lifecycleScope.launchWhenCreated {
       viewModel.myLiveData.observe(viewLifecycleOwner, {
           renderState(ViewState.SuccessfulFetch(it))
       })
   }
}
Anybody know why the first case queries the database upon screen rotation, while the second does not? Thanks!
b
In your 1st example you’re observing
databaseStuff()
which is a function creating a new liveData every time it is called which happens when your fragment gets recreated
n
Thank you!