Eli-Fox / LEGO-Catalog

A LEGO® Catalog app illustrating current Android Architecture state using Android development best practices.
https://medium.com/@eli.fox/android-architecture-starring-kotlin-coroutines-jetpack-mvvm-room-paging-retrofit-and-dagger-7749b2bae5f7?sk=9c5a7af2fbf5d4a04e72322bfb245489
Apache License 2.0
766 stars 186 forks source link

LiveData is not reloaded when back is pressed and returned back to app #4

Open eugeneroz opened 5 years ago

eugeneroz commented 5 years ago

Reproduce steps:

  1. Open app and browse themes are loaded
  2. Data is loaded from network
  3. Press back button
  4. Open app again

Actual: Data is presented without loading it from network

Expected: Data should be loaded from network

mfsi-prateeksharma commented 4 years ago

Hi @eugeneroz For that, you need to change the approach of initializing the live data in viewmodel from lazy to var or val, var example: () -> LiveData<Result<SampleResponse>> = { repository.sample(createRequest()) }

prakashreddyofferly commented 4 years ago

use like this `var liveData: LiveData<Result<List>> ? = null private var mediatorLiveData: MediatorLiveData<Result<List>> = MediatorLiveData<Result<List>>()

fun refresh(): MediatorLiveData<Result<List<Product>>> {
    Log.d("info_refresh","refresh2")
    if(liveData!=null&&liveData?.hasObservers()!!){
      liveData?.removeObservers(lifecycleOwner!!)
    }
    liveData = repository.products()
    try{
        if(mediatorLiveData.hasObservers()){
            Log.d("info_refresh","removing observers")
            mediatorLiveData?.removeObservers(lifecycleOwner!!)
        }
    }catch (exc : Exception){
        Log.d("info_refresh","exception: "+exc.message)
        exc.printStackTrace()
    }
    mediatorLiveData.addSource(liveData!!, object : Observer<Result<List<Product>>> {
        override fun onChanged(@Nullable recipeListPojos: Result<List<Product>>) {
            mediatorLiveData.setValue(recipeListPojos)
        }
    })
    return mediatorLiveData
}`

in repository add this method fun products (): LiveData<Result<List<Product>>> { Log.d("info_refresh","products refresh info") return resultLiveData( databaseQuery = { dao.getProductsLiveData() }, networkCall = { ProductRemoteDataSource.fetchProductList("",0,20) }, saveCallResult = { dao.insertAll(it.results!!) }) }

vignesh6 commented 4 years ago

liveData?.removeObservers(lifecycleOwner!!)

@prakashreddyofferly How do you get lifecycleOwner inside viewmodel

mfsi-prateeksharma commented 4 years ago

@vignesh6 you can follow my approach, and let me know in case of any problem