Do I need to call removeObserver for lifecycle, upon its onDestroy() event? [duplicate]
Asked Answered
O

2

9

This is a very simple question:

Background

I'm using the relatively new Lifecycle class (part of the android architecture components libraries) to handle some events of the Activity/Fragment in an easier way.

This is how you use it for handling ON_DESTROY event:

            lifecycle.addObserver(object : LifecycleObserver {
                @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                fun onDestroy() {
                    lifecycle.removeObserver(this)
                    //Do something
                }
            })

The problem

I can't find in the docs and here, whether I should call removeObserver or that it's done automatically anyway upon the ON_DESTROY event.

What I've tried

I tried to read about it, and for now as a precaution I always call removeObserver .

The question

Is it safe to avoid calling removeObserver upon ON_DESTROY event?

Orlando answered 16/8, 2018 at 7:49 Comment(3)
AFAIK , no need to call removeObserve explicitly. github.com/googlecodelabs/android-lifecycles/issues/5Lepidopterous
@Lepidopterous Why not put it in an answer so that I could accept it? Seems they wrote that it's not needed on this case...Orlando
I should not get credit of another developers solution. still if you want then I can do it so other community member can take proper readable solution :)Lepidopterous
L
10

There is one chain of discussion over github related this topic.

As far as I know, there is no need to call removeObserve explicitly.

The only reason is that lifecycle-aware components are specifically designed to make sure the observer is removed.

Here is the link to where this is discussed: https://github.com/googlecodelabs/android-lifecycles/issues/5

Lepidopterous answered 16/8, 2018 at 10:8 Comment(0)
V
-1

In my point, if you call lifecycle.addObserver in application, you don't have to call removeObserver, when the application is destroyed, the process would be killed also. If you call lifecycle.addObserver in an activity, you need to call removeObserver on OnDestroy method.

Vierno answered 16/8, 2018 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.