Skip to content

Commit

Permalink
馃悰 Handled Back Pressed
Browse files Browse the repository at this point in the history
  • Loading branch information
aritra-tech committed Jul 30, 2023
1 parent bc42055 commit 8e73822
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.aritra.notify.components.actions

import androidx.activity.compose.BackHandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import com.aritra.notify.utils.closeApp
import com.aritra.notify.utils.toast
import kotlinx.coroutines.delay


@Composable
fun BackPressHandler() {
var exit by remember { mutableStateOf(false) }
val context = LocalContext.current

LaunchedEffect(key1 = exit) {
if (exit) {
delay(2_000L)
exit = false
}
}

BackHandler(enabled = true) {
if (exit) {
context.closeApp()
} else {
exit = true
context.toast("Press again to exit")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.aritra.notify.R
import com.aritra.notify.components.actions.BackPressHandler
import com.aritra.notify.components.actions.LayoutToggleButton
import com.aritra.notify.components.actions.NoList
import com.aritra.notify.components.actions.SwipeDelete
Expand All @@ -50,6 +51,8 @@ fun HomeScreen(
navigateToUpdateNoteScreen: (noteId: Int) -> Unit
) {

BackPressHandler()

val viewModel = hiltViewModel<HomeScreenViewModel>()
val listOfAllNotes by viewModel.listOfNotes.observeAsState(listOf())
var searchQuery by rememberSaveable { mutableStateOf("") }
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/java/com/aritra/notify/utils/CommonExtensions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.aritra.notify.utils

import android.content.Context
import android.widget.Toast
import com.aritra.notify.ui.screens.MainActivity

fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun Context.closeApp() {
(this as? MainActivity)?.finish()
}

0 comments on commit 8e73822

Please sign in to comment.