Open fjr619 opened 4 years ago
Hi @fjr619
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()) }
var example: () -> LiveData<Result<SampleResponse>> = { repository.sample(createRequest()) }
with this approach how we trigger that from button in activity or fragment?
i'm new in kotlin can you explain about this part
var example: () -> LiveData<Result<SampleResponse>>
what is that ?
@fjr619 no problem,
viewModel.example().observe(viewLifecycleOwner, Observer { result ->
when (result) {
is Result.Success -> {
progressBar.visibility = View.GONE
Timber.d("response === %s", result.data.email)
}
is Result.Loading -> {
progressBar.visibility = View.VISIBLE
}
is Result.Error -> {
progressBar.visibility = View.GONE
}
}
})
Let me know if it works for you.
so i create a function for observe in activity
private fun subscribeUI() {
viewModel.example().observe(viewLifecycleOwner, Observer { result ->
when (result) {
is Result.Success -> {
progressBar.visibility = View.GONE
Timber.d("response === %s", result.data.email)
}
is Result.Loading -> {
progressBar.visibility = View.VISIBLE
}
is Result.Error -> {
progressBar.visibility = View.GONE
}
}
})
}
then in my activity will become
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
subscribeUI() //this is for first time request
btnRetry.setOnClickListener {
subscribeUI() //this is for retry request
}
}
is it correct?
@fjr619 yes, I assume you have everything initialized and injected as per the project. In case you still get the issue, you can provide me your sample project at pratzz.sharma@gmail.com or create a private repo
my other question, i assume with MVVM it will resolve change orientation problem, but when i rotate my phone, it will trigger calling API again, how to solved it? I read that in ViewModel we can use
init {
callAPI()
}
to solve the problem, it doesn't with LEGO-Catalog example pattern
with this pattern, it is really easy to use, but i have a problem to retry call API when got error, because we already have livedata in repository and calling api in datasource, how we can get retry request with this pattern?