How get_it flutter package deals with Garbage Collector as it registers all the instance at start - flutter

I have a naive question, I have read about the flutter dependency injection package get_it, it registers all the instances at start like the service locator design pattern, my question is how it deals with a garbage collector and when it frees the objects? Does it store all the instances in memory at start till app lifeCycle?
To be honest, I know very little about Service locator design pattern otherwise I might have understood this package clearly, Now I need your help on how it works under the hood? what if we need to register an instance at run time with some dynamic data coming from API then how can we do that?
Your help will be appreciated thanks in advance

Per the documentation, you can unregister a previously registered instance as follows:
/// Unregister an [instance] of an object or a factory/singleton by Type [T] or by name [instanceName]
/// if you need to dispose some resources before the reset, you can
/// provide a [disposingFunction]. This function overrides the disposing
/// you might have provided when registering.
void unregister<T>({Object instance,String instanceName, void Function(T) disposingFunction})
Service objects are often need throughout the life of an application, in which case you'll never need to unregister.

Related

What are the memory management differences between Get.put(SomeClass(), permanent: true) and Get.put(SomeGetXService())

I am using Getx and its dependency injection mechanism.
sometime I am overthinking - should I inject a class that should remain in memory (for good as a Singelton) using
Get.put(SomeClass(), permanent: true)
or using
Get.put(SomeGetXService())
by reading the documentation, both ways seems to put the class in memory as Singelton, and it can only be deleted explicitly (i.e. not with Get.smartManagement).
as for me, I prefer not to extend the class with GetxService, since the first option is simpler to implement - but I feel like I might be missing something. having the class in memory as Singelton through out the app life-span is a must.
Thanks for your help
The first option always keeps the class in memory throughout the entire app's lifespan, while the second option binds the service to the stack navigation lifecycle. According to GetX dpcumentation, a GetXService is only deleted with a call to Get.reset(). In most cases though, both methods will probably be equally valid, since in essence, a service is kept in memory throughout the entire app lifecycle anyways.

Always resolve type in new Lifetimescope?

Is there a way to make Autofac to always resolve types in a new lifetimescope?
ie.
Container.Resolve<MyHandler>().Whatever();
Now i have to do like this:
Container.BeginLifetimeScope().Resolve<MyHandler>().Whatever();
It would be nice to be able to inject MyHandler into a class and know that MyHandler is it own scope.
Autofac does not provide a way to automatically start a new lifetime scope per component resolution.
Creating a lifetime scope is actually a process you need to control very tightly. Lifetime scopes not only help the scoping of component resolution, but also manage the deterministic disposal of components you resolve. From a memory management perspective, you shouldn't just fire up lifetime scopes without also disposing of them when you're done. Failing to dispose your created scopes can very easily cause a memory leak.
This is why you always see BeginLifetimeScope in a using statement or in a very tightly integrated scenario like ASP.NET request lifetime - so you can start a scope at a known spot and be sure to end/dispose of it. Child lifetime scopes are not automatically disposed for you once they're created - it's up to you to do that cleanup.
The Autofac wiki has some good information on lifetime scopes here.

Android State Machine

I write an Android application. I have a lot of Activities in my application with a large number of transitions between Activities. I decided to realize a state machine, which will switch my activities.
I hoped to realize a State Machine in my Application class or its subclass, but I can't start any Activity from it.
public class MainAppClass extends Application {}
the code like this is failing:
Intent intent = new Intent();
intent.setClass(this.MyActivity, Screen2Activity.class);
StartActivity(intent);
Maybe, is it unreal? Are there other methods for such tasks?
Thanks for your answers!
Here's another question: Why are you trying to start an activity from a subclass of Application?
Read this (from the documentation) and you'll see why what you are trying to do doesn't make any sense.
The Application class is the base class for those who need to maintain global application state. There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
If you edit your original post, clarifying why you are trying to do this, perhaps I can point you to a more suitable means of launching your Screen2Activity.

Zend 2 Event Listeners in classes not loaded

Does the Zend 2 event manager have the ability to fire listeners in classes that are not loaded?
If I understand you correctly, then I believe that you can register listeners using the StaticEventManager (see Event Manager Quick Start).
In this case, you do not need to have an instance of the target class (just the name), but you can register listeners for events (typically methods) on future instances of that target class that may occur.
Of course, in order to be useful, the target class should actually compose an EventManager instance (probably via an events() method, as described on the same Quick Start page) and actually fire the events.
I confess that I am still trying to wrap my own head around the ZF2 EventManager, so if I have totally boned it up here, please feel free to correct me.

Cross-Activity references using GWT with Gin

I have a GWT MVP application using Activities and Places. This is inspired by Mauro Bertapelle's sample (in this thread), apparently based on some of Thomas Broyer's work.
Here's the problem: I have LoginActivity make an RPC call, which for a successful login, returns a User. This user has a role (e.g., admin, regular user, guest). Several Views and Activities, including a NavigatorView, depend on this role for what they show or do. How do I get this User instance to the other Activities?
I do not have a ClientFactory; injection (Gin) is used for instantiating the Views in the ActivityProviders which provide my Activities/Presenters, and the ActivityProviders are injected into my ActivityMapper. So this may reduce to a Gin question: how do I get the user reference where it's needed? This seems to be similar to this SO question about global references in MVP.
Consider me a Gin newbie, this is my first attempt at using it. I'm guessing there is a "Gin way" to make this happen, but I don't know Gin well enough to know the best way to do this (if Gin should be used at all).
Much thanks.
Edit 1: Despite my best efforts searching SO for a similar question, I just found this question which is pretty much identical to mine (is the SO algorithm for finding "Related" links better than the search?). I'm thinking that the Gin answer by David is on the right track.
I don't think that an EventBus solution is possible. I'm following the Google guidelines which involve instantiating Activity at every Place change, so a single Event by itself will not suffice.
Something that I'm using on the server-side with Guice, and would work just as well on the client-side, is to bind to a custom Provider. In your case though, you'd have to make the provider a singleton and push the value into it from your RPC callback (rather than pulling it from some context).
You'd first need a specific provider:
#Singleton
public class CurrentUserProvider implements Provider<User> {
private User currentUser;
public User get() { return currentUser; }
public void setCurrentValue(User currentUser) {
this.currentUser = currentUser;
}
}
You'd bind User to the provider: bind(User.class).toProvider(CurrentUserProvider.class)
In your RPC callback you'd inject a CurrentUserProvider so you can setCurrentValue but everywhere else you'd inject Provider<User> to keep CurrentUserProvider as an implementation detail. For very short-lived objects, you could directly inject a User value rather than a Provider<User>.
If you need to notify objects of the value change, you could dispatch an event on the global event bus.
Alternately, you could always use the concrete CurrentUserProvider type (which wouldn't have to implement Provider anymore) and possibly make it a HasValueChangeHandlers so you could register listeners on it rather than on the event bus (but you'd have to clean-up after yourself in your activities' onStop and onCancel to avoid memory leaks, whereas it's taken care of automatically if you register handlers on the event bus in onStart).
(if you ask me, I'd rather go away with authenticating from within the app whenever possible)
I had similar requirements on a recent project.
When I get a reply from login (or logout) RPC I send a custom AuthenticationEvent on EventBus. All activities that are interested in this listen for this event. AuthenticationEvent has a reference to AppUser object which is null if user just logged out. AppUser contains all necessary data (privileges, groups, etc..) so that activities can inspect it and act upon it.
About global references: you can have a class with static methods providing data that you need. This class internally holds singleton references to needed instances. In my example I have static method AppUtils.getCurrentUser(). Internally it holds a reference to AppUser and also listens to AuthenticationEvent to set/reset this field.
As a side note: don't rely on client side to enforce access restrictions - you should separate your RPC servlets into two groups: public and private. Public can be accessed by anybody (this is basically login/logout RPC and some other public info RPC), while private RPC requires user to be authenticated. Access restrictions can be set per path/servlet: http://code.google.com/appengine/docs/java/config/webxml.html#Security_and_Authentication
Update:
As you noted, class with static methods is not advisable in this setup, because it is not replaceable and this prevents testing (which is the whole point of using GIN).
The solution is to inject a utility class holding globals (AppUtils) into activities that need the globals. AppUtils should be declared singleton in GIN configuration as one instance is enough for the whole app.
To use Provider or not is just a question if you want to delay the initialization of dependencies (AppUtil is dependency). Since AppUtils is a singleton for the whole app it makes no sense to have it lazy initialized.
Sometimes you will have a situation where you have multiple Activities shown on screen (in my case it was MenuBar and InfoBar). In this case, when user logs in you will need a way to notify them of the change. Use EventBus.