3

The onDispose callback isn't called when i close my app or when its process is killed. Is this intended behavior? Is there a different callback for this event? Can I make my own, by somehow passing MainActivitys onStop callback down to a composable?

The reason I need this sort of callback is because I want to save some data, that the user entered, to the database when the user leaves the screen or on process death. I learned that SavedStateHandle is made for this use case, but only for small amounts of data - I want to save complex, non-parcelable data and I don't want the code overhead that SavedStateHandle seems to have.

My current workaround is to save to the database on every change, which isn't hard since my code is reactive using coroutine StateFlow. I fear that this has performance implications, but maybe I'm wrong and this is the best solution.

Noah
  • 2,718
  • 3
  • 17
  • 23

1 Answers1

1

Killed as in force stopped/swipped from recents? If yes, then this is expected behavior, composer is disposed when viewLifecycle is in ON_DESTROY state.

From the source:

 override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            dispose()
        } else if (event == Lifecycle.Event.ON_CREATE) {
            if (!disposed) {
                setContent(lastContent)
            }
        }
    }

If ON_DESTROY is not dispatched, the composer will not dispose. ProcessLifecycle will not be helpful either.

onDestroy is no reliable in such case, you should await for either onStop or onPause, onDispose should be used to dispose any operations/resources that are related to the view.

Nikola Despotoski
  • 49,966
  • 15
  • 119
  • 148
  • When you say "you should await for either onStop or onPause", do you mean I should wait until these callbacks are implemented in jetpack compose? I'm not sure I understand – Noah Jan 11 '21 at 14:21
  • I meant implementing your own `LifecycleObserver`. – Nikola Despotoski Jan 11 '21 at 14:42
  • 1
    If you're implementing your own `LifecycleObserver` why not use the `onDestroy` from there ? – Biscuit Sep 30 '22 at 19:24