androidandroid-architecture-componentsandroid-architecture-lifecycle

Implementing the new Android Architecture Components with Activity and Fragments


Currently I try implementing an application with the architecture components provided by android. In terms of only using activities in the UI Package there is no problem with that, but if I implement several fragments which are held by one activity in a fragment container I'll get in trouble. The communication for data requests using fragments should never be called from the fragments itself but from its activity. In this case only the activity will register the needed viewmodel but the lifecycle of each fragment isn't handled properly... how can I face this problem using multiple fragments in one activity requesting data from a server and be lifecycleaware for the fragments even when the activity is calling the viewmodel(s)?


Solution

  • I´m not sure if I understood you right. You want to load data in your Activity for your Fragment with the lifecycle awareness of your Fragment?

    Maybe you can try to access the ViewModel of your Fragment from the Activity to get an FragmentLifecycle aware ViewModel. And than you can query data via this ViewModel.

    viewModel = ViewModelProviders.of(YourFragment).get(FragmentViewModel.class);
    

    I´m not sure if this works or if this is a good idea. The google guide only shows it the other way around, accessing the ViewModel from the Activity within the Fragment, to share data between Fragments, or Activity and Fragment.