1

What I'm doing

I'm implementing oauth2 process to my android app. After user authorized the app via browser, my app will launch an activity to retrive the authorization code from intent, and then use the code to get the access token for APIs.

I have a method in viewMomodel with repository injected, to proceed the get access token API:

@HiltViewModel
class MainActivityViewModel @Inject constructor(
    private val repository: AuthRepository
) : ViewModel() {


fun getAccessToken(authCode: String) {
...
}
...
}

Get viewModel in the activity:

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    private val viewModel : MainActivityViewModel by viewModels()
...
}

In the activity, the authorization code can be retrieved like this:

//retrive code from intent
val authCode = intent.data.getQueryParameter("code")

Question

My question is, how can I pass the authCode from activity to viewModel and call the getAccessToken function from viewModel's init block?

@HiltViewModel
class MainActivityViewModel @Inject constructor(
    private val repository: AuthRepository,
    private val authCode: String //how to pass this parameter?
) : ViewModel() {

init {
   //Want to call getAccessToken here
   getAccessToken(authCode)
}
fun getAccessToken(authCode: String) {
...
}
...
}

I have read this amazing article https://medium.com/mobile-app-development-publication/passing-intent-data-to-viewmodel-711d72db20ad and got the idea that savedStateHandle could provide key-value pair of Intent data. But in mycase, the authCode is stored in intent.data but not intent.extras bundles, is it still possible to get the data from savedStateHandle?

If not, I think another solution is creating a custom ViewModelFactory to pass arguments, but I'm new with dagger hilt and not sure how to achieve this. It would be very appreciated if someone could give me some guide... Thanks.

  • Call `getAccessToken` directly from the activity passing the `authCode`. Won't that work for you? – Arpit Shukla Nov 21 '21 at 14:24
  • @ArpitShukla Thank you for the comment. Hmmm yes actually I can do this but just wondering if the method can be executed at the begining of viewmodel's creation, then I don't have to call it explicitly somewhere from Activity. – Shadow_Land Nov 21 '21 at 15:06

2 Answers2

2

You need to annotate authCode with @Assisted and also create a custom viewModelFactory. You can find more about this here https://proandroiddev.com/whats-new-in-hilt-and-dagger-2-31-c46b7abbc64a

0

just use autogenerated ViewModel.savedStateHandler parameter, which has all intent arguments from your MainActivity

@HiltViewModel
class ExampleViewModel @Inject constructor(
  private val savedStateHandle: SavedStateHandle,
  private val repository: ExampleRepository
) : ViewModel() {
  ...
}

Doc

Sorry, it's a bit late answer, but might be useful for anybody.

sanya5791
  • 433
  • 4
  • 5