Navigation component navigate inside a onActivityResult not working
Asked Answered
D

2

5

i am using
navController.navigate(R.id.FragmentB) to navigate from host fragment in MainActivity to navigate to different fragments and it works like expected except inside onActivityResult it won't respond ,i am returning an ID from other activity and want to navigate to Fragments depending on that ID but it is not responding ,

Deleterious answered 11/3, 2020 at 15:50 Comment(0)
D
2

It turns out that i needed to create a Coroutine and run my navigation function on it , i tried with :

  GlobalScope.launch(Dispatchers.Main) {
    navigate()
    }

and it works fine, obviously gotta need to optimise my coroutine ,but that was the main issue

Deleterious answered 11/3, 2020 at 16:44 Comment(3)
Sounds like internally it's a handler.post.Mcneal
can you explain more ?Deleterious
By invoking a coroutine that would run in Main dispatcher, internally it invokes Handler.post, which means that onActivityResult -> onStart -> onResume runs before your code. If you do it directly in onActivityResult, then onStart hasn't run, the NavController says its state is restored, and it ignores your navigate call.Mcneal
H
4

If you're not using coroutines, a simple Handler() will do the trick.

Handler().post {
    navigate()
}
Holocene answered 24/4, 2020 at 11:24 Comment(0)
D
2

It turns out that i needed to create a Coroutine and run my navigation function on it , i tried with :

  GlobalScope.launch(Dispatchers.Main) {
    navigate()
    }

and it works fine, obviously gotta need to optimise my coroutine ,but that was the main issue

Deleterious answered 11/3, 2020 at 16:44 Comment(3)
Sounds like internally it's a handler.post.Mcneal
can you explain more ?Deleterious
By invoking a coroutine that would run in Main dispatcher, internally it invokes Handler.post, which means that onActivityResult -> onStart -> onResume runs before your code. If you do it directly in onActivityResult, then onStart hasn't run, the NavController says its state is restored, and it ignores your navigate call.Mcneal

© 2022 - 2024 — McMap. All rights reserved.