https://kotlinlang.org logo
#compose
Title
# compose
j

julioromano

03/02/2021, 10:18 AM
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

allan.conda

03/02/2021, 10:25 AM
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

Ian Lake

03/02/2021, 3:02 PM
The correct answer is to not use a
launchMode
at all. NavController will handle deep links for you then
a

allan.conda

03/02/2021, 3:03 PM
Right, forgot about deep links support in the Navigation library.
j

julioromano

03/02/2021, 4:42 PM
@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

Ian Lake

03/02/2021, 5:20 PM
No, you should never use
singleTask
either. That breaks implicit deep links on other app's tasks (something that Navigation also fully supports)
🙏 1
250 Views