In iOS, it is a good practice to remove listeners when a view controller disappears. So is it the same in Android world? Should I remove all listeners in onPause()
of an activity
Asked
Active
Viewed 631 times
1

Jack Guo
- 3,959
- 8
- 39
- 60
1 Answers
1
If we're talking about good practices you shouldn't have your listeners in your Activity
in the first place. Whenever a configuration change (e.g. screen rotation) happens your Activity
will call onPause
, onStop
, onDestroy
, onCreate
, onStart
, onResume
. If your listener is in your Activity
rebuilding the ui on configuration changes will take way longer than needed. Google's own solution for this issue is ViewModel
in the Architecture Components library. The listeners should be in your ViewModel
or maybe even a Repository
that's called from the ViewModel
. It's all explained in more detail in the provided link.

Sander
- 808
- 6
- 18
-
Yes I know. Still, should I detach listeners in view model when activity disappears? – Jack Guo Jul 31 '18 at 15:38
-
You should extend `LiveData`, start listening in the `onActive` and detach the listener in `onInactive`, expose the extended LiveData object through the `ViewModel` and observe it from the `Activity`. This way it will handle all the complicated lifecycles for you making your app more reliable and your code easier to read. – Sander Jul 31 '18 at 15:55