0

See the following kotlin code:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        val disposable = Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
                               .subscribe { textView.text = it.toString }
    }

}

Here I am am passing a lambda expression in the subscribe method instead of an anonymous inner classses. So is it required to call disposable.dispose() in order to prevent memory leaks? Or the lambda expression won't keep an implicit reference to the instance of the MainActivity class.

And if I do need to dispose it, what is the best way and why?

itstauq
  • 81
  • 6

1 Answers1

0

I added a logger to the Observable.subscribe() as follows:

class MainActivity : AppCompatActivity() {

        override fun onCreate(savedInstanceState: Bundle?) {
            val disposable = Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).subscribe {
                                Log.d(TAG, "Interval:" + it.toString())
                                textView.text = it.toString 
                            }
        }

    }

and noticed that even after exiting the app by pressing the back key, the observable kept running. So I added the following code to onDestroy():

override fun onDestroy() {
    disposable.dispose()
    super.onDestroy()
}

and now everything is working as expected

itstauq
  • 81
  • 6