2

I'm writing an Android application with Dagger 2, Retrofit and I want use the AccountManager utilities.

I need to provide the OkHttpClientwith a specific Authenticator that refresh the auth-token using the AccountManagerFuture calls. The code is pretty similar to this one:

@Provides
@Singleton
OkHttpClient provideOkHttpClient() {
    return new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                // TODO: Refresh the authToken using the AccountManagerFuture call.

                // ...
            }
    });
}

Question

The @Provides annotation allows only synchronous dependencies, but I know that the @Produces manages also the asynchronous ones. Can I use @Produces to provide AccountManagerFuture calls (ex. #addAccount or #getAuthToken)?

My proposal

I'm a bit confuse about it, but I would give you my proposal. I didn't try, but it seems to do the same things two times...

@Produces
AccountManagerFuture<Bundle> produceRefreshAuthToken(AccountManager accountManager) {
    return accountManager.getAuthToken(accountType, authTokenType, null, activity, new AccountManagerCallback<Bundle>() {
            @Override
            public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
                try {
                    // Get the future result.
                    Bundle future = accountManagerFuture.getResult();
                    // Get the authToken.
                    String authtoken = future.getString(AccountManager.KEY_AUTHTOKEN);


                } catch (OperationCanceledException | AuthenticatorException | SecurityException | IOException ex) {

                }
            }
        }, null);

}

@Provides
@Singleton
OkHttpClient provideOkHttpClient(AccountManagerFuture<Bundle> future) {
    return new OkHttpClient.Builder()
        .authenticator(new Authenticator() {
            @Override
            public Request authenticate(Route route, Response response) throws IOException {
                 // Get the result.
                 Bundle bundle = future.getResult();
                 // Get the auth-token.
                 String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);

                // ...
            }
    });
}
Samuele Colombo
  • 685
  • 2
  • 6
  • 20

0 Answers0