Skip to content

Commit

Permalink
Created ComposeNavigator.currentKeyAsState() function
Browse files Browse the repository at this point in the history
  • Loading branch information
chRyNaN committed Dec 19, 2021
1 parent 0a6c810 commit a4b67e7
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,40 @@ val navigator = rememberNavigatorByKey("Hello") { key ->
}
```

##### Key State changes

The key of the currently displayed `@Composable` can be accessed by the `ComposeNavigator.currentKey` property:

```kotlin
navigator.currentKey
```

To listen to changes to the current key, use the `ComposeNavigator.keyChanges` property along with
the `Flow<T>.collectAsState` function:

```kotlin
val currentKey by navigator.keyChanges.collectAsState(initial = currentKey)
```

For convenience, there is an extension function that performs the above logic: `ComposeNavigator.currentKeyAsState()`
This is especially useful when a `@Composable` needs to be updated when the key changes, for instance in a Bottom
Navigation component:

```kotlin
val currentKey by navigator.currentKeyAsState()

BottomNavigation {
listOf(ScreenIntent.ColorList, ScreenIntent.Palette).forEach {
BottomNavigationItem(
selected = currentKey == it,
onClick = {
navigator.goTo(it)
}
)
}
}
```

#### Android

To create a `Navigator` use one the provided `navigator()` functions. For instance:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@file:Suppress("unused")

package com.chrynan.navigation.compose

import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState

/**
* Obtains the changes to the [ComposeNavigator.currentKey] value and returns it as a [State]. This allows it to be
* used in a [Composable] and cause recomposition when the value changes.
*
* If you just need to get the current key value and do not need to cause recomposition when the value changes, simply
* use the [ComposeNavigator.currentKey] property.
*
* **Note:** Internally this function uses the [ComposeNavigator.keyChanges] Flow and the [collectAsState] function
* using the [ComposeNavigator.currentKey] as the initial value.
*
* @see [ComposeNavigator.currentKey]
* @see [ComposeNavigator.keyChanges]
* @see [collectAsState]
*/
@ExperimentalNavigationApi
fun <T> ComposeNavigator<T>.currentKeyAsState(): State<T?> = keyChanges.collectAsState(initial = currentKey)

0 comments on commit a4b67e7

Please sign in to comment.