How to solve the memory leak caused by the re-asynchronization of RxJava subscriptions?

because the subscribed content must be executed on a new thread, at first I thought I needed to wait to avoid memory leaks, but after that, the memory still leaked

< H2 > fragment < / H2 >
class MemoryLeakFragment : Fragment() {

    lateinit var disposable: Disposable
    
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        disposable = Observable.create<String> {

            val lock = Object()

            Thread {

                Thread.sleep(1000)

                it.onNext("")
                
                synchronized(lock) { lock.notify() }

            }.start()

            synchronized(lock) { lock.wait() }

            it.onComplete()

        }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    Toast.makeText(context, it, Toast.LENGTH_LONG).show()
                }, {
                    Toast.makeText(context, it.message, Toast.LENGTH_LONG).show()
                }, {
                    Toast.makeText(context, "end", Toast.LENGTH_LONG).show()
                })
    }
    override fun onDestroy() {
        if (!disposable.isDisposed)
            disposable.dispose()
        super.onDestroy()
    }
}
< H2 > activity < / H2 >
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val button = AppCompatButton(this)
        button.setOnClickListener({
            supportFragmentManager.beginTransaction()
                    .replace(android.R.id.content, TestFragment())
                    .addToBackStack(null).commit()
        })
        setContentView(button)
    }

    override fun onBackPressed() {
        if (supportFragmentManager.backStackEntryCount == 0)
            Toast.makeText(this, "exit", Toast.LENGTH_SHORT).show()
        else super.onBackPressed()
    }
}

fragment

Mar.20,2021

is not too clear of kolin, but memory leakage depends on whether your subscription is unsubscribed. Generally speaking, there will be no memory leakage as long as you cancel the subscription after it is no longer in use.

Menu