Can I recreate a managed dependency in Dagger2?

I'm considering the possibility of providing a Singleton GoogleApiClient at the Application scope. Multiple Activities and Fragment require the client and there is a lot of boilerplate code.

What do I do if the injected dependency gets into a state that I need to throw it away and create a new one?

I have encountered a real case where the GoogleApiClient throws an IllegalStateException. It is extremely rare, but at this point, reconnect() does not help. The only way to recover is to establish a new connection to the API client (using GoogleApiClient.Builder).

Answers


You can use provider injection to indicate that some code must be run every time a dependency is needed. An overview of this is covered in the user guide (scroll down to the heading "Provider injections"). You then implement and inject a Provider that knows how to retrieve a known working instance of your GoogleApiClient.

The trick here is that I think your concrete implementation of Provider will need some way for you to indicate to it that the held object is no longer valid and should be recreated. So, when you detect there is a problem, you will end up having to cast it to the concrete type and invoke another method to tell it what happened. Or find some other way to direct the provider logic to recover from a bad object.


There is no way to indicate a scoped dependency needs to be refreshed without just recreating an instance of the component. If it's not necessary that the GoogleApiClient is shared across injection sites, then make it unscoped. If it is, then you'd need to do something kinda hacky and manage the isDirty configuration on your own and pass this information to the module. But I wouldn't recommend anything like this.


Need Your Help

Simple inquiry on a very small jQuery plugin

javascript jquery jquery-plugins

Here's a fairly newbish question: Testing out a simple function where it fades out on hover and fades back in on mouseout. Was playing around with parameters so please excuse how this doesn't make a