Another way you can use is as follows
Let's do it step by step :)
First Step :
the ViewModel must implement the DefaultLifecycleObserver interface
@HiltViewModel
class LoginViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle
) : ViewModel(), DefaultLifecycleObserver {
}
in this way you can acess this methods:
public interface DefaultLifecycleObserver extends FullLifecycleObserver {
/**
* Notifies that {@code ON_CREATE} event occurred.
* <p>
* This method will be called after the {@link LifecycleOwner}'s {@code onCreate}
* method returns.
*
* @param owner the component, whose state was changed
*/
@Override
default void onCreate(@NonNull LifecycleOwner owner) {
}
/**
* Notifies that {@code ON_START} event occurred.
* <p>
* This method will be called after the {@link LifecycleOwner}'s {@code onStart} method returns.
*
* @param owner the component, whose state was changed
*/
@Override
default void onStart(@NonNull LifecycleOwner owner) {
}
/**
* Notifies that {@code ON_RESUME} event occurred.
* <p>
* This method will be called after the {@link LifecycleOwner}'s {@code onResume}
* method returns.
*
* @param owner the component, whose state was changed
*/
@Override
default void onResume(@NonNull LifecycleOwner owner) {
}
/**
* Notifies that {@code ON_PAUSE} event occurred.
* <p>
* This method will be called before the {@link LifecycleOwner}'s {@code onPause} method
* is called.
*
* @param owner the component, whose state was changed
*/
@Override
default void onPause(@NonNull LifecycleOwner owner) {
}
/**
* Notifies that {@code ON_STOP} event occurred.
* <p>
* This method will be called before the {@link LifecycleOwner}'s {@code onStop} method
* is called.
*
* @param owner the component, whose state was changed
*/
@Override
default void onStop(@NonNull LifecycleOwner owner) {
}
/**
* Notifies that {@code ON_DESTROY} event occurred.
* <p>
* This method will be called before the {@link LifecycleOwner}'s {@code onDestroy} method
* is called.
*
* @param owner the component, whose state was changed
*/
@Override
default void onDestroy(@NonNull LifecycleOwner owner) {
}
}
Second Step:
In your Composable, call the method that I have sent to the attachment as below.
create an extension function like this:
@Composable
fun <LO : LifecycleObserver> LO.observeLifecycle(lifecycle: Lifecycle) {
DisposableEffect(lifecycle) {
lifecycle.addObserver(this@observeLifecycle)
onDispose {
lifecycle.removeObserver(this@observeLifecycle)
}
}
}
Call it in your composable as follows
@Composable
fun LoginScreen(viewModel: LoginViewModel) {
viewModel.observeLifecycle(LocalLifecycleOwner.current.lifecycle)
}
Thirst Step:
Implement your logic in ViewModel and if you are going to go to another page, inform Composable by Event
LoginViewModel.kt
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
}