Android: When to register and register for notifications?

I use the Notifications interface to update snippets every time the data changes.

 public interface Notifications { void register(ID id, Listener listener); void unregister(ID id, Listener listener); <T> void post(ID id, T value); interface Listener<T> { void onEvent(ID id, T value); } enum ID { CustomersUpdated, ProductsUpdated } } 

As for Android Lifecycle , what is the best way to register and unregister for notifications?

Android Lifecycle

Here are a few scenarios:

Scenario 1:

 public class ProductsListFragment extends BaseFragment implements Notifications.Listener { @Override public void onStart() { mAdapter.notifyDataChanged(); register(Notifications.ID.ProductsUpdated, this) super.onStart(); } @Override public void onStop() { unregister(Notifications.ID.ProductsUpdated, this) super.onStop(); } @Override public void onEvent(Notifications.ID id, Object value) { mAdapter.notifyDataChanged(); } 

Scenario 2:

 public class ProductsListFragment extends BaseFragment implements Notifications.Listener { @Override public void onResume() { mAdapter.notifyDataChanged(); register(Notifications.ID.ProductsUpdated, this) super.onResume(); } @Override public void onPause() { unregister(Notifications.ID.ProductsUpdated, this) super.onPause(); } @Override public void onEvent(Notifications.ID id, Object value) { mAdapter.notifyDataChanged(); } 

Please explain why you suggest to use this or that implementation .. or another!

+4
source share
2 answers

There is no universal answer to this question. onResume / onPause will most likely expect the expected behavior most of the time, but you may encounter situations where you want to do this sooner or later.

In another note, however, there are two points about style and functionality - call super.onResume as the first that is used in the method (and super.onStop as the last). Thus, your loop is completely nested in a "super" loop, and you avoid strange errors and edge cases. Also, it is not always recommended to call notifyDataSetChanged in onResume . In fact, this is probably a pretty wasteful idea.

+2
source

I would stick with scenario 2. Although the order in which onPause() and onResume() is linear for fragments, the same does not apply to actions.

fragment_lifecycle

Since the pause and resume of fragments is called up whenever an action occurs, translations will be received whenever an asset is active. However, activity does not call onStop() until it loses its visibility. In this case, the fragments will still process the translations, while the activity in which it is contained is inactive, which is not a good idea for me.

+1
source

All Articles