3

I have application that has MainActivity, that starts InvoiceActivity and that starts InvoicePaymentActivity which finally starts PaymentSuccessActivity.

I started using architecture components and it seems to work fine, bud I have found problem when starting MainActivity from PaymentSuccessActivity.

Up until now, I would just start new Intent and the app would "reset" to main screen. With ViewModel I am getting "Cannot add the same observer with different lifecycles".

I have found 2 solutions, but cannot think which one is better:

  1. Subscribe to observer in onResume, unsubscribe onPause

  2. Finish all previous activities except MainActivity after the next one is started. So when I just finish PaymentSuccessActivity, user will be on MainActivity. This has a drawback of user navigating backwards...

But it seems I cannot add the observer again... how can I unsibscribe/subscribe? My code does not work right now...

override fun onResume() {
    super.onResume()
    viewModel.intercom.observe(this, observer)  
}


override fun onPause() {
    super.onPause()
    viewModel.intercom.removeObserver { observer }
}
kvgr
  • 325
  • 4
  • 17

1 Answers1

1

So this whole problem was base on using anonymous Observer class. Once I created my observer class implementing observer interface, the app startet to work fine, without needing to manually observer/remove. Can anyone explain why this is issue?

kvgr
  • 325
  • 4
  • 17
  • I came up with this issue today and it looks like the problem comes from JVM object reuse. I had simple anonymous class observer that only logged the value and I was crashing when moving between fragments. As soon as I added fragments field to the log problem disappeared since my observer was no longer "stateless" (it was capturing its host fragment). See [When does JVM decide to reuse old lambda?](https://stackoverflow.com/questions/29674645/when-does-jvm-decide-to-reuse-old-lambda). – Pawel Oct 30 '20 at 21:00