Equivalent of startActivityForResult() with Android Architecture Navigation

Jonas Schmid picture Jonas Schmid · Jun 5, 2018 · Viewed 15.2k times · Source

I have a workflow with 3 screens. From "screen 1" to access to "screen 2", the user must accept some kind of terms and conditions that I call in my picture "modal". But he only has to accept those conditions once. The next time he is on the first screen, he can go directly to screen 2. The user can chose to NOT accept the terms, and therefore we go back to "screen 1" and do not try to go to "screen 2".

App workflow

I am wondering how to do it with the new navigation component.

Previously, what I would do it:

  • On screen 1, check if the user must accept the conditions
  • If no, start "screen 2" activity
  • If yes, use startActivityForResult() and wait result from the modal. Mark the terms as accepted. Start "screen 2"

But with the navigation graph, there is no way to start a Fragment to obtain a result.

I could mark the terms as accepted in the "modal" screen and start the "screen 2" from there. The thing is that to access to the screen 2, I need to do a network request. I do not want to duplicate the call to the API and processing its outcome in both "screen 1" and "modal".

Is there a way to go back from "modal" to "screen 1" with some information (user accepted the terms), using Jetpack navigation?

Edit: I currently get around it by using the same flow that Yahya suggests below: using an Activity just for the modal and using startActivityForResult from the "screen 1". I am just wondering if I could continue to use the navigation graph for the whole flow.

Answer

AntPachon picture AntPachon · Apr 16, 2019

There are a couple of alternatives to the shared view model.

  1. fun navigateBackWithResult(result: Bundle) as explained here https://medium.com/google-developer-experts/using-navigation-architecture-component-in-a-large-banking-app-ac84936a42c2

  2. Create a callback.

ResultCallback.kt

interface ResultCallback : Serializable {
    fun setResult(result: Result)
}

Pass this callback as an argument (note it has to implement Serializable and the interface needs to be declared in its own file.)

<argument android:name="callback"
                  app:argType="com.yourpackage.to.ResultCallback"/>

Make framgent A implement ResultCallback, fragment B by will get the arguments and pass the data back through them, args.callback.setResult(x)