The problem is that Dagger will not be able to provide callbacks, since callbacks are implementation details, not dependencies, and callbacks are usually set before creating the client (see option 2 below for callbacks for more details).
One option is for Dagger to provide GoogleApiClient.Builder
, and then your implementation should end the chain by setting callbacks and calling build()
:
@Provides @Named("location_api") GoogleApiClient.Builder provideLocationClient(Context context) { return new GoogleApiClient.Builder(context) .addApi(LocationServices.API); } @Provides @Named("geodata_api") GoogleApiClient.Builder provideGeodataClient(Context context) { return new GoogleApiClient.Builder(context) .addApi(Places.GEO_DATA_API); }
Please note the changes:
@Named(..)
already a scope, so you should abandon @Singleton
- it is not needed.- Two provider methods must be named differently (
provideLocationClient
, provideGeodataClient
) - Instead of returning
GoogleApiClient
module returns GoogleApiClient.Builder
.
Now, to use this dependency, you must insert a constructor, and then attach your callbacks and build the client:
@Inject @NamedScope("location_api") GoogleApiClient.Builder mLocationClientBuilder; ... mComponent.inject(this); mClient = mLocationClientBuilder.<addCallbacks(...)>.build(); mClient.connect();
If you taunt this builder using the unit test framework, you will need to make a callback to the callback and call the onConnected(Bundle)
callback method when you call connect()
.
Another option is to provide GoogleApiClient
as you were, but then you must remember to register your callbacks before connecting, and you must remember to cancel these callbacks when you are done (to prevent memory leak). See GoogleApiClient # registerConnectionCallbacks ( )
source share