Working on an Android app where each user can have multiple accounts under the same login. There is a single activity with a fragment per tab - based on the Android sample Bottom Navigation.
On one of the tabs is a calendar, which is hooked up to a ViewModel like so:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val calendarViewModel = ViewModelProvider(this).get(CalendarViewModel::class.java)
calendarViewModel.calendarEvents.observe(viewLifecycleOwner) {
// Code that modifies the UI to show the events on a given day
}
val progressBar: ProgressBar = binding.progressBar
calendarViewModel.calendarState.observe(viewLifecycleOwner) {
// Progress bar / error state handling code
}
}
On one of the other fragments (different tab in the bottom tab bar), I allow the user to switch accounts. When I come back to the calendar fragment/tab, the viewModel is still in scope so I have incorrect data for this user.
How can I manually force the ViewModelProvider to recreate the viewModel in onCreateView? Is there some way I can invalidate the ViewModel scope and force a re-pull of the data?
Related
Scenario: I have 2 fragments ProductList and ProductDetail in my nav graph. And when i click on any product it opens the ProductDetail fragment using findNavController.navigate() method.
Problem: The problem is when I go back from ProductDetail to ProductList fragment, the ProductList fragment reloads again and it also calls the api to fetch products list, which I want to avoid.
If anyone knows the reason behind it or the solution to this particular issue please let me know in comments.
You should cache the fetch result locally, pull from the cache either during a fetch attempt or upon failure of a fetch attempt. This is a very common pattern on mobile.
Finally I got the answer from somewhere, so I am posting the sample code to resolve the issue I am facing -
private lateinit var contentView: View
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
if (!::contentView.isInitialized) {
binding = FragmentNewProductListBinding.inflate(layoutInflater)
contentView = binding.root
// initialize your views or set click listeners or call apis
}
return contentView
}
Note: To elaborate, there is some internal bug in the navigation library where it draws the previous fragment from scratch when going back from another fragment. So as a workaround or temporary patch, what we can do is just check whether the view is already initialized or not, if yes then don't create it again.
Hope you understand the reasoning and answer.
I have a code like this:
private val appViewModel: AppViewModel by activityViewModels()
private lateinit var user: User
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// This sets the variable user to the value collected from a StateFlow from appViewmodel
lifecycleScope.launchWhenCreated {
appViewModel.user.collect { flowUser -> user = flowUser }
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// This method utilizes the lateinit user variable
lifecycleScope.launchWhenStarted {
doThingWithUser()
}
return binding?.root
}
Since the value of StateFlow persists even after being collected, after the screen rotates the first lifecycleScope.launchWhenCreated gets called, collects the flowUser from the flow again, assigns it to the lateinit user variable, and doThingWithUser gets called later and everything works fine.
But after two or more rotations, this stops being the case, for some reason user doesn't get initialized, doThingWithUser gets called and the app crashes with kotlin.UninitializedPropertyAccessException.
What am I doing wrong? Does the value from StateFlow vanishes after two collections/screen rotations? Something happens with the actual flow inside the ViewModel? Something happens with the onCreate and onCreateView methods? Or does launchWhenStarted and launchWhenCreated behave differently after two rotations?
Thanks.
I found out what the problem was. Apparently the Navigation Component messes with the order of the fragment's lifecycles, as seen here.
So when the screen rotated, due to the backstack order, the Navigation was creating another fragment that also interacts with the StateFlow of the ViewModel before the current Fragment. So, the other fragment onCreate method was sending something else to the flow, and therefore messing my current fragment collection.
The solution is to either make the flow collection independent of the fragment lifecycle, or change the collection in either one of the trouble fragments.
When nav component switches to a fragment, I get this "Views added to a FragmentContainerView must be associated with a Fragment" crash. What causes this?
I didn't see this mentioned anywhere and it took a while to figure out but in this case, I was trying to set up a old legacy fragment while migrating to the nav arch component.
The reason was in the frag's onCreateView, the inflate looked like:
layoutView = inflater.inflate( R.layout.home, container, false );
The last argument automatically attaches the view to the container. This works fine in old style fragments and activities. It does not work with the nav arch component because the root container is a FragmentContainerView which only allows fragments to be attached to it.
Setting the last argument to false makes it work properly.
Just replace your onViewCreated method.
class MyFragment : Fragment() {
override fun onCreateView( inflater: LayoutInflater,container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_post,container,false)
}
}
If you are working with lifeCycleScope, make sure you launch and run the block at least in Lifecycle.State.STARTED state.
I am using Navigation library and my use case is preserve Fragment state on back press which I achieve by returning already inflated binding in onViewCreated as when changing fragments Navigations seems not to destroy already existing instance of this fragment the actual view variable exists when you navigate there back or up.
But I also have a use case when I need to recreate this Fragment instance so I expect to have a way to call onDestroy() for that fragment. But I don't see any api for removing/obtaining existing in the backstack instances.
So my question is how to get an existing instance of a Fragment from nav back stack and destroy it or just remove it by calling nav controller api.
some code:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewModel = ViewModelProviders.of(requireActivity(), mViewModelFactory)
.get(MainViewModel::class.java)
parseNavigationExtra()
return if (::mBinding.isInitialized) {
mBinding.root
} else {
//create new binding
}
so when I call this action I still get the old binding root as the variable is still present.
<action
android:id="#+id/clearBackStack"
app:destination="#+id/mainFragment"
app:launchSingleTop="true"
app:popUpTo="#+id/mobile_navigation"
app:popUpToInclusive="true" />
List<Fragment> fragments = getActivity().getSupportFragmentManager().getFragments();
Fragment lastFragment = fragments.get(fragments.size() - 1);
getActivity().getSupportFragmentManager().beginTransaction().remove(emptyDialog);
changes in the navigation library since 2.1.0
NavBackStackEntry: You can now call NavController.getBackStackEntry(), passing in the ID of a destination or navigation graph on the back stack. The returned NavBackStackEntry provides a Navigation-driven LifecycleOwner, ViewModelStoreOwner (the same returned by NavController.getViewModelStoreOwner()), and SavedStateRegistryOwner, in addition to providing the arguments used to start that destination.
So the plan is to use the new api to see what is available for NavBackStackEntry.
I'm using a shared ViewModel in Navigation component rather than creating a ViewModel for every fragment (mostly because it's easier) but now I have a problem when I re-enter a fragment and subscribe to the ViewModel live data of that fragment, I get the last state also too.
here is the ViewModel Code:
val apiLessonData: MutableLiveData<String>> = MutableLiveData()
fun getLessonsUserCreated() =
apiCall(MyMaybeObserver(apiLessonData))
in MyMaybeObserver, I have somthing like this:
override fun onSuccess(t: T) {
apiDataObserver.postValue(t)
}
and this is how I observe it in my fragment:
private val apiAddGoalData = Observer<String> { response ->
showSnack(response)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
.
.
viewModel.apiAddGoalData.observe(viewLifecycleOwner, apiAddGoalData)
.
.
}
now when I enter the first time it works fine but I open it the second time, it shows the snack from the previous time, how to stop this without creating new ViewModel?
In the simple way You could set null for your MutableLiveData after getting data in onchange method of the observer. For more information you can read this article:livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case
. also you can see this question maybe help you: How to clear LiveData stored value?
I don't think your problem is with the LiveData since you are wisely using the viewLifecycleOwner, problem is with the state of the view and lifeCycle of the fragment. With navigation component of jetpack, fragments get replaced in the container. Think of this scenario: You open fragment A then you navigate to frament B and press back button to return to fragment A. onCreateView and onViewCreated methods of the fragment A gets called again. Since the onDestroy of fragment A haven't been called when you opened fragment B some of the view states will be restored while returning to A. This is as you might know the same reason we use viewLifecycleOwner. So Nullify or clear the state of the views in the onDestroyView of the fragment A:
recyclerView.setAdapter(null)
checkBox.setChecked(false)