I have stumbled upon this quite trivial, but tricky problem. I have spent a decent amount of time searching official docs, but unfortunately found no answer.
Official docs say that you should pass an instance of NavController
down to @Composable
-s, and call it as onClick = { navController.navigate("path") }
. But what happens if I have to trigger navigation event from ViewModel (ex. redirect on login, redirect to newly created post page)? Awaiting any coroutine (ex. HTTP request) in @Composable
would be not just bad, but probably force Android to kill app because of the blocked UI thread
Unofficial solutions (documented mostly if form of Medium articles) are based on the concept of having a singleton class and observing some MutableStateFlow
containing path.
That sounds stupid in theory, and doesn't help much in practice (not side-effect and recomposition friendly, triggers unnecessary re-navigation).
MutableStateFlow
containing path is the right way – Barnette