Search code examples
androidandroid-architecture-componentsandroid-livedata

LiveData does not call LifecycleRegistryOwner if standard Fragment is used


I'm trying to use the standard Android fragments together with LiveData. The update is triggered by updates in a Room Database. Unfortunately my observer is not triggered.

Example code:

public class MyListFragment extends Fragment implements LifecycleRegistryOwner {

LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

@Override
public LifecycleRegistry getLifecycle() {
    return mLifecycleRegistry;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

// ... normal code

    AppDatabase database = AppDatabase.getDatabase(getContext());
    LiveData<List<RssItem>> allRssItems = database.rssItemDao().getAllRssItems();
    allRssItems.observe(this, rssItems -> setListContent(rssItems));

}

If I enforce to ignore the lifecycle events, I receive the updates.

 allRssItems.observeForever(new Observer<List<RssItem>>() {
        @Override
        public void onChanged(@Nullable List<RssItem> rssItems) {
            Toast.makeText(getContext(), "Update", Toast.LENGTH_SHORT).show();
            setListContent(rssItems);
        }
    });

Can someone spot my error? I'm not using the v4.Fragment but the standard Android one but as I copied the implementation from LifecycleFragment into my code, I assume that this should work.


Solution

  • The comment from CommonsWare and the link to the bug solve this question. For standard fragment you need trigger yourself the corresponding lifecycle events, e.g., lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);