One of the strengths of Navigators is that they can be composed into a larger structure. This allows for modular and reusable blocks in your application. When composing Navigators, you have the same freedom as you have with regular Navigators which means that you can choose your own internal model to represent the state.
When composing Navigators, you usually create a Navigator that exclusively deals with other Navigator instances directly, instead of mixing Scenes and Navigators together.
The base implementations below show an overview of the default composite Navigator classes.
CompositeReplacingNavigator1
The CompositeReplacingNavigator class is the composite version of the ReplacingNavigator, and can switch between several child navigators.
1 class MyCompositeNavigator(
2 savedState: NavigatorState?
3 ) : CompositeReplacingNavigator(savedState) {
4
5 override fun initialNavigator() : Navigator {
6 return MyFirstNavigator()
7 }
8
9 fun onEvent() {
10 replace(MySecondNavigator())
11 }
12
13 override fun instantiateNavigator(
14 navigatorClass: KClass<out Navigator<*>>,
15 state: NavigatorState?
16 ) : Navigator<out Container> {
17 return when(navigatorClass) {
18 MyFirstNavigator::class -> MyFirstNavigator(state)
19 MySecondNavigator::class -> MySecondNavigator(state)
20 else -> error("Unknown navigator class: $navigatorClass")
21 }
22 }
23 }
CompositeStackNavigator1
The CompositeStackNavigator class is the composite version of the StackNavigator, and uses a stack to model its internal state.
1 class MyCompositeNavigator(
2 savedState: NavigatorState?
3 ) : CompositeStackNavigator(savedState) {
4
5 override fun initialStack() : List<Navigator> {
6 return listOf(MyFirstNavigator())
7 }
8
9 fun onEvent() {
10 push(MySecondNavigator())
11 }
12
13 override fun instantiateNavigator(
14 navigatorClass: KClass<out Navigator<*>>,
15 state: NavigatorState?
16 ) : Navigator<out Container> {
17 return when(navigatorClass) {
18 MyFirstNavigator::class -> MyFirstNavigator(state)
19 MySecondNavigator::class -> MySecondNavigator(state)
20 else -> error("Unknown navigator class: $navigatorClass")
21 }
22 }
23 }
1: This class is available in the ext-acorn
artifact.