您可以使用的另一种方法如下
让我们一步一步来吧:)
第一步 :
ViewModel 必须实现 DefaultLifecycleObserver 接口
@HiltViewModel
class LoginViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle
) : ViewModel(), DefaultLifecycleObserver {
}
通过这种方式,您可以访问此方法:
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) {
}
}
第二步:
在您的可组合项中,调用我发送到附件的方法,如下所示。
像这样创建一个扩展函数:
@Composable
fun <LO : LifecycleObserver> LO.observeLifecycle(lifecycle: Lifecycle) {
DisposableEffect(lifecycle) {
lifecycle.addObserver(this@observeLifecycle)
onDispose {
lifecycle.removeObserver(this@observeLifecycle)
}
}
}
在您的可组合项中调用它,如下所示
@Composable
fun LoginScreen(viewModel: LoginViewModel) {
viewModel.observeLifecycle(LocalLifecycleOwner.current.lifecycle)
}
解渴步骤:
在 ViewModel 中实现您的逻辑,如果您要转到另一个页面,请通过事件通知 Composable
LoginViewModel.kt
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
}