How to call `NavController` from `Activity.onNewIn...
# compose
j
How to call
NavController
from
Activity.onNewIntent()
?
I used to do this 👇 with fragment navigation, but now I’m not sure how to grab a reference to
NavController
within
onNewIntent()
which is outside of the composition.
Copy code
override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    navController.handleDeepLink(intent)
  }
For instance: I’ve tried grabbing a ref to
NavController
as a side effect with
.apply
like:
Copy code
setContent {
        val navController = rememberNavController().apply {
          navController = this // navController is a global instance var
But I end up getting crashes at runtime because that global var is not initialized yet when
onNewIntent()
is called.
a
Have you tried making a SideEffect with Intent as key? not sure if that’s a bad idea, but might work.
Copy code
private var intent : Intent? by mutableStateOf(null)

fun onNewIntent(newIntent) {
  intent = newIntent
}

setContent {
  val navControler = ...
  SideEffect(Intent) {
    navController...
  }
}
actually, that idea looks horrible lol. If you’re using ViewModel, I think you can update the navigation state depending on the intent, Then your composable navigates based on the navigation state..
i
The correct answer is to not use a
launchMode
at all. NavController will handle deep links for you then
a
Right, forgot about deep links support in the Navigation library.
j
@Ian Lake though
launchMode="singleTask"
still seems a legit use case for single activity apps. It wouldn’t make sense for those apps to have multiple instances of their activity created by the system. What to do in such case? Docs are currently mentioning this here: https://developer.android.com/reference/kotlin/androidx/navigation/NavController#handledeeplink
i
No, you should never use
singleTask
either. That breaks implicit deep links on other app's tasks (something that Navigation also fully supports)
🙏 1
464 Views