the question is similar on Where should I call Rest API in fragment
but i want to discuss about the right on code.
i have call an api from oncreateView()
for example
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
GlobalScope.launch {
showHomeViewModel("someState")
}
}
in function showHomeViewModel() i have defined condition for adapter
private suspend fun showHomeViewModel(state: String) {
withContext(Dispatchers.Main) {
viewModel.liveData().observe(viewLifecycleOwner, observer)
if(adapter.itemCount == 0) callApi() else Log.d(TAG_LOG, "nothing todo")
}
}
so its calling if the data == 0
but i have searchView component , when i navigate to other fragment and back to first fragment , the observer is null...
private val observer =
Observer<MutableList<DataItem>> { item ->
Log.d(TAG_LOG, "observer data $item") // always null if i have ever navigate to other fragment
if (item != null)
adapter.setData(item)
binding.progress.gone()
}
the problem is solve when i remove the condition adapter.itemCount == 0.
but the lifecycle my device always call api when screen or fragment appear.
before i always put the callApi from onResume(), but in my course should i put to the onCreateView and other explain should in onViewCreate() but the main problem is , **its good the code if i use the condition adapter.itemCount == 0 ? to perform searachView , where i defined on viewModel for search (liveData) **
i was tried to from adapter Filterable to perform search but its not work with liveData, so i use my viewModel instead of filterable.