Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Inside LifecycleObserver

8766b19fe1c1f8475e233c910ed6440f?s=47 kobito-kaba
July 18, 2018
29

Inside LifecycleObserver

How to handle components' lifecycle in Android app developing.

8766b19fe1c1f8475e233c910ed6440f?s=128

kobito-kaba

July 18, 2018
Tweet

Transcript

  1. Hiroyuki Mori @moridroid Inside LifecycleObserver

  2. Lifecycle Problems in Android

  3. in early days https://developer.android.com/guide/components/activities/activity-lifecycle.html

  4. today Steve Pomeroy https://github.com/xxv/android-lifecycle CC-BY-SA 4.0

  5. case 1: fetching data every onCreate

  6. case 1: fetching data every onCreate

  7. case 1: fetching data every onCreate

  8. case 1: fetching data every onCreate

  9. case 1: fetching data every onCreate

  10. case 1: fetching data every onCreate Wasteful

  11. case 2: showing after activity’s death

  12. case 2: showing after activity’s death

  13. case 2: showing after activity’s death

  14. case 2: showing after activity’s death Crash !!

  15. case 3: forgetting to stop observing

  16. case 3: forgetting to stop observing

  17. case 3: forgetting to stop observing

  18. case 3: forgetting to stop observing memory leak

  19. Handling lifecycles

  20. Lifecycle library

  21. Observer pattern

  22. None
  23. None
  24. None
  25. None
  26. None
  27. None
  28. ×

  29. None
  30. None
  31. None
  32. loose coupled

  33. None
  34. None
  35. Event Channel

  36. None
  37. notify events

  38. observe

  39. None
  40. Inside Lifecycle library

  41. subscribing lifecycle events

  42. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

      ... lifecycle.addObserver(yourObservable) } }
  43. public class LifecycleRegistry extends Lifecycle { @Override public void addObserver(@NonNull

    LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
  44. public class LifecycleRegistry extends Lifecycle { @Override public void addObserver(@NonNull

    LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
  45. static class ObserverWithState { ... ObserverWithState(LifecycleObserver observer, State initialState) {

    mLifecycleObserver = Lifecycling.getCallback(observer); ... } void dispatchEvent(LifecycleOwner owner, Event event) { ... mLifecycleObserver.onStateChanged(owner, event); ... } }
  46. static class ObserverWithState { ... ObserverWithState(LifecycleObserver observer, State initialState) {

    mLifecycleObserver = Lifecycling.getCallback(observer); ... } void dispatchEvent(LifecycleOwner owner, Event event) { ... mLifecycleObserver.onStateChanged(owner, event); ... } }
  47. publishing lifecycle events

  48. public class SupportActivity extends Activity implements LifecycleOwner { ... protected

    void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); } ... }
  49. public class ReportFragment extends Fragment { ... public void onActivityCreated(Bundle

    savedInstanceState) { dispatch(Lifecycle.Event.ON_CREATE); } public void onStart() { dispatch(Lifecycle.Event.ON_START); } public void onResume() { dispatch(Lifecycle.Event.ON_RESUME); } public void onPause() { dispatch(Lifecycle.Event.ON_PAUSE); } public void onStop() { dispatch(Lifecycle.Event.ON_STOP); } ... }
  50. public class ReportFragment extends Fragment { ... private void dispatch(Lifecycle.Event

    event) { ... if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } }
  51. ObserverWithState AdapterObserver Adapter FooObserver ReportFragment SupportActivity LifecycleRegistry addObserver attach dispatch

    event sync
  52. ReportFragment SupportActivity LifecycleRegistry attach dispatch event

  53. FooObserver ReportFragment SupportActivity LifecycleRegistry addObserver attach dispatch event

  54. ObserverWithState AdapterObserver Adapter FooObserver ReportFragment SupportActivity LifecycleRegistry addObserver attach dispatch

    event sync
  55. Subscriber Publisher EventChannel subscribe publish event fire event

  56. How to use

  57. example: Observing network state

  58. None
  59. None
  60. without LifecycleObserver

  61. class NetworkStateReceiver(private val callback : (NetworkInfo?) -> Unit) : BroadcastReceiver()

    { override fun onReceive(context: Context?, intent: Intent?) { val conn = context?.getSystemService(ConnectivityManager::class.java) ?: return callback(conn.activeNetworkInfo) } } Step1 : Create a BroadcastReceiver
  62. receiver = NetworkStateReceiver { if (it != null && it.isConnected)

    { textView.text = "online" } else { textView.text = "offline" } } Step2 : create an instance create an instance
  63. Step3 : register it at onResume override fun onResume() {

    super.onResume() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(receiver, filter) } register at onResume
  64. override fun onPause() { super.onPause() unregisterReceiver(receiver) } Step4 : unregister

    it at onPause unregister at onPause
  65. override fun onPause() { super.onPause() unregisterReceiver(receiver) } Step5 : Never

    forget to unregister unregister at onPause Don’t miss it
  66. with LifecycleObserver

  67. enum class Connectivity { OFFLINE, ONLINE } class NetworkObservable( private

    var activity: Activity?, private val callback : (Connectivity) -> Unit) : LifecycleObserver { private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { callback(Connectivity.ONLINE) } else { callback(Connectivity.OFFLINE) } } } Step1 : Wrap the receiver
  68. enum class Connectivity { OFFLINE, ONLINE } class NetworkObservable( private

    var activity: Activity?, private val callback : (Connectivity) -> Unit) : LifecycleObserver { private val receiver = NetworkStateReceiver { if (it != null && it.isConnected) { callback(Connectivity.ONLINE) } else { callback(Connectivity.OFFLINE) } } } Step1 : Wrap the receiver implements LifecycleObserver
  69. @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { activity?.registerReceiver(receiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver()

    { activity?.unregisterReceiver(receiver) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun release() { activity = null } Step2 : register / unregister at lifecycle events
  70. @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun registerReceiver() { activity?.registerReceiver(receiver, IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)) } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun unregisterReceiver()

    { activity?.unregisterReceiver(receiver) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun release() { activity = null } Step2 : register / unregister at lifecycle events @OnLifecycleEvent
  71. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    ... lifecycle.addObserver( NetworkObservable(this) { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } }) } } Step3 : Use it !
  72. class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {

    ... lifecycle.addObserver( NetworkObservable(this) { if (it == Connectivity.ONLINE) { textView.text = "online" } else { textView.text = "offline" } }) } } Step3 : Use it ! easy to use
  73. Conclusion

  74. Lifecycle Management

  75. Lifecycle Management - is a hard and hassle task

  76. Lifecycle Management - is a hard and hassle task -

    can cause problems
  77. Lifecycle Management - is a hard and hassle task -

    can cause problems The Lifecycle library
  78. Lifecycle Management - is a hard and hassle task -

    can cause problems The Lifecycle library - provides the feature to observe lifecycles
  79. Lifecycle Management - is a hard and hassle task -

    can cause problems The Lifecycle library - provides the feature to observe lifecycles - can create lifecycle-aware components easily
  80. Hiroyuki Mori @moridroid Thank you