Calling arguments?.clear()
is not sufficient. Reason for that is that the navArgs()
delegate holds all arguments in a local cached variable. Moreover, this variabel is private:
(taken from NavArgsLazy.kt)
private var cached: Args? = null
override val value: Args
get() {
var args = cached
if (args == null) {
...
args = method.invoke(null, arguments) as Args
cached = args
}
return args
}
I also find this approach pretty stupid. My use-case is a deeplink that navigates the user to a specific menu item of the main screen in my app. Whenever the user comes back to this main screen (no matter wherefrom), the cached arguments are re-used and the user is forced to the deeplinked menu item again.
Since the cached
field is private and I don't want to use reflections on this, the only way I see here is to not use navArgs
in this case and get the arguments manually the old-school way. By doing so, we can then null them after they were used once:
val navArg = arguments?.get("yourArgument")
if (navArg != null) {
soSomethingOnce(navArg)
arguments?.clear()
}