From 8a146754f2c1c95244cbe00dd9c6b9e582658f57 Mon Sep 17 00:00:00 2001 From: Amir Nasrollahzadeh Date: Mon, 7 Jul 2025 12:46:27 +0330 Subject: [PATCH] Feat: Add auto-save functionality on screen stop event --- .../opennote/presentation/screen/NoteScreen.kt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/app/src/main/java/com/yangdai/opennote/presentation/screen/NoteScreen.kt b/app/src/main/java/com/yangdai/opennote/presentation/screen/NoteScreen.kt index 98e9ba7..a8aba7a 100644 --- a/app/src/main/java/com/yangdai/opennote/presentation/screen/NoteScreen.kt +++ b/app/src/main/java/com/yangdai/opennote/presentation/screen/NoteScreen.kt @@ -102,6 +102,10 @@ import androidx.compose.ui.util.fastJoinToString import androidx.core.content.FileProvider import androidx.core.net.toUri import androidx.hilt.navigation.compose.hiltViewModel +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.yangdai.opennote.MainActivity import com.yangdai.opennote.R @@ -163,6 +167,8 @@ fun NoteScreen( val noteTextDetails by viewModel.textState.collectAsStateWithLifecycle() val dataAction by viewModel.dataActionStateFlow.collectAsStateWithLifecycle() val appSettings by viewModel.settingsStateFlow.collectAsStateWithLifecycle() + val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current + // 确保屏幕旋转等配置变更时,不会重复加载笔记 var lastLoadedNoteId by rememberSaveable { mutableStateOf(null) } @@ -178,6 +184,18 @@ fun NoteScreen( } } + DisposableEffect(lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_STOP) { + viewModel.onNoteEvent(NoteEvent.SaveOrUpdate) + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + } + } + val context = LocalContext.current val coroutineScope = rememberCoroutineScope() val pagerState = rememberPagerState(pageCount = { 2 })