0

I have following view model and observer in A Fragment(in onViewCreated) which populates the recyelerview using adapter

commonOwnDBViewModel =
                new ViewModelProvider(requireActivity()).get(CommonOwnDBViewModel.class);
        Observer<List<FolderEntity>> notesObserver =
                FolderEntityList -> {
                    folderNameAdapter.setListManager(FolderEntityList);
                    recyclerView.getAdapter().notifyDataSetChanged();
                    Toast.makeText(mActivity, "" + FolderEntityList.size(), Toast.LENGTH_SHORT).show();
                };
        commonOwnDBViewModel.getAllFolderEntityList
                ().observe(requireActivity(), notesObserver);

it gives me a list and works fine in the fragment now I want to use the same list in A service using Viewmodel and Observer how can we do that how do we manage Lifecycle in service.

1234567
  • 2,226
  • 4
  • 24
  • 69

1 Answers1

0

Instead of using normal service, use LifecycleService.

You can get the lifecycle of the service by calling getLifecycle() method and pass this lifecycle to your observer.

More details here: https://developer.android.com/reference/androidx/lifecycle/LifecycleService

Alpha 1
  • 4,118
  • 2
  • 17
  • 23
  • so should we use commonOwnDBViewModel = new ViewModelProvider(getLifecycle()).get(CommonOwnDBViewModel.class); ?? – 1234567 Oct 18 '21 at 06:23