Home > Software design >  Instantiate viewModel with run-time arguments using Hilt
Instantiate viewModel with run-time arguments using Hilt

Time:11-22

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.

CodePudding user response:

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

  • Related