1

Suppose I am Observing a LiveData in a Fragment and I want to remove observer after I received the data.

eg:

val testLiveData = MutableLiveData<String>()

and Observing as:

testLiveData.observe(this, Observer<String> {
        //TODO://Remove this Observer from here
        //testLiveData.removeObserver(this)
    })

How can I do that? Calling "this" is giving me an instance of the Fragment instead of the current Observer.

However, I can do like this.

 testLiveData.observe(this, object : Observer<String>{
        override fun onChanged(t: String?) {
            testLiveData.removeObserver(this)
        }

    })

Is there any way to do the same in SAM?

a.r.
  • 565
  • 1
  • 6
  • 18

1 Answers1

1

In the first case you cannot access this since it is not guaranteed that every invocation of observe creates a new instance of Observer<String>. If the lambda does not access any variable within the function where it is defined, the corresponding anonymous class instance is reused between calls (i.e., a singleton Observer is created that is used for every observe call).

Thus, for implementing listeners, the second variant (object : Observer<String>) should be used. This enforces that a new Observer is created every time observe is called, which in turn can then be accessed as this within its implemented methods.

Markus Weninger
  • 11,931
  • 7
  • 64
  • 137