Shared State
Learning Objectives
- You know of the benefits of inversion of control and dependency injection in creating widgets that share state.
One of the key benefits in using inversion of control and dependency injection is that they are used to create a pool of dependencies that can be shared in the application. This is in particular useful, when the state needs to be shared between different parts of an application, or when the state needs to be made available to multiple parts of the application.
Let’s start with an example that does not use inversion of control or dependency injection, but instead creates a new instance of the controller in every part of the application.
When you try out the above application, you will notice that the count is not shared between the ClickDisplay
and the ClickCounterView
widgets — whenever the button is clicked, the text starting with “Likes” is updated, but the text starting with “Clicks so far” is not updated
This is because a new instance of CountController
is created in each widget. As the state is specific to the controller, the state is not shared between the widgets.
However, if we use inversion of control and dependency injection, we can create a shared controller that is used in both widgets. This way, the state is shared between the widgets, and the count is updated in both widgets when the button is clicked.
When you try out the application below, you see that the changes to the count are reflected in both the “Likes” and “Clicks so far” texts.