Skip to content

Instantly share code, notes, and snippets.

@KaustubhPatange
Last active June 5, 2022 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KaustubhPatange/834799cc826e02cf99e6720684b3032c to your computer and use it in GitHub Desktop.
Save KaustubhPatange/834799cc826e02cf99e6720684b3032c to your computer and use it in GitHub Desktop.
// 1. Setup simple-stack (lot of things has been omitted for brevity)
// For a complete setup, https://github.com/Zhuinden/simple-stack-compose-integration/blob/master/README.md#what-does-it-do
class MainActivity : AppCompatActivity() {
private val composeStateChanger = ComposeStateChanger()
override fun onCreate(savedInstanceState: Bundle?) {
...
val backstack = Navigator.configure()
.setScopedServices(DefaultServiceProvider()) // <-- Support for scoped services
.setStateChanger(AsyncStateChanger(composeStateChanger))
.install(this, findViewById(R.id.container), History.of(FirstKey())) // <-- Initial destination is FirstKey, line: 31
setContent {
BackstackProvider(backstack) {
composeStateChanger.RenderScreen()
}
}
}
override final fun onBackPressed() {
if (!Navigator.onBackPressed(this)) {
super.onBackPressed()
}
}
}
// 2. Define destinations
@Immutable @Parcelize
data class FirstKey(private val noArgsPlaceholder: String = ""): DefaultComposeKey(), DefaultServiceProvider.HasServices {
override val saveableStateProviderKey: Any = this // <-- Important for `rememberSaveable`s
override fun getScopeTag(): String = javaClass.name // <-- tag
override fun bindServices(serviceBinder: ServiceBinder) {
serviceBinder.add(FirstModel()) // <-- Registering service of class FirstModel
}
@Composable
override fun ScreenComposable(modifier: Modifier) {
val vm = rememberService<FirstModel>() // <-- Using the required service
//.. content
}
}
@Immutable @Parcelize
data class SecondKey(private val name: String): DefaultComposeKey() {
@Composable
override fun ScreenComposable(modifier: Modifier) {
// Retrieving the sample instance of FirstModel if the destination
// exists in the backstack & is parent to the current.
val vm = rememberService<FirstModel>(FirstKey.getScopeTag())
//.. content
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment