Skip to content

Instantly share code, notes, and snippets.

@zsoltk
Created December 22, 2019 12:54
Show Gist options
  • Save zsoltk/38b24494594b38ffcbd96f53c19eedac to your computer and use it in GitHub Desktop.
Save zsoltk/38b24494594b38ffcbd96f53c19eedac to your computer and use it in GitHub Desktop.
@Composable
fun <T> BackHandler(routing: T, children: @Composable() (BackStack<T>) -> Unit) {
// grab the parent handler, wherever it's up the tree
val upstream = +ambient(backPressHandler)
// to keep track of children down the tree
val downstream = +memo { ScopedBackPressHandler() }
// let's have a default back stack on this level
val backStack = BackStack(routing)
// our lambda for handling back press: asking all children,
val handleBackPressHere: () -> Boolean = { downstream.handle() || backStack.pop() }
// register our handler in the parent handler
upstream.handlers.add(handleBackPressHere)
// remove ourselves from the parent handler when this level goes away
+onDispose { upstream.handlers.remove(handleBackPressHere) }
// override the ambient so that it points to this level
// so that we'll become the upstream of some child later:
backPressHandler.Provider(value = downstream) {
// add client code Composable, which will have access to back stack:
children(backStack)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment