Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
eugeneroz opened this issue Oct 22, 2019 · 4 comments
Open

Comments

@eugeneroz
Copy link

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
Copy link

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
Copy link

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
Copy link

vignesh6 commented Jun 23, 2020

liveData?.removeObservers(lifecycleOwner!!)

@prakashreddyofferly How do you get lifecycleOwner inside viewmodel

@mfsi-prateeksharma
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants