How to make an object disposable in Dart? - dart

I have an abstract class named AbstractFoo and its implementation, Foo. Foo also implements an interface Bar. I would like to make Foo disposable so I assume that I need to implement Disposable class but I am getting an error
Classes and mixins can only implement other classes and mixins
I tried to make AbstractFoo implement Disposable but I get the same error. Can anyone help?

There is no automatic disposal system built into Dart. You are referencing the w_common package.
According to the page you linked, you will need to define classes you want to be disposed something like this:
class MyDisposable extends Object with Disposable {
MyDisposable() {
var thing = new ThingThatRequiresCleanup();
getManagedDisposer(() {
thing.cleanUp();
return new Future(() {});
});
}
}
For more specific help, please edit your question to include code.

Related

Is it possible to initialize a library?

I am trying out the new Dart FFI in making wrappers for libsodium. Libsodium needs to be initialized with calling init(). But I don't think the user should be burdened to remember this and I also wouldn't like to check some global state variable.
I know that Go has package init() functions which run when a package gets included. Is there something similar in Dart?
Of course I could just wrap everything up into a class and run init() in the constructor but there isn't much sense in instatiating a class which basically only exposes static methods. Besides, I would like to preserve the procedural style of libsodium.
Of course I could just wrap everything up into a class and run init() in the constructor but there isn't much sense in instatiating a class which basically only exposes static methods. Besides, I would like to preserve the procedural style of libsodium.
You could have a singleton instance and expose library functions as methods on the instance, and you could provide a public getter function that automatically does initialization.
For example, something like:
Libsodium? _instance;
Libsodium get libsodium => _instance ??= Libsodium._();
class Libsodium {
Libsodium._() {
// Do initialization.
}
void foo() {
// ...
}
void bar() {
// ...
}
}
and then callers would need to use it via:
import 'libsodium.dart';
libsodium.foo();
This would hide the class instantiation and wouldn't look any different to callers than if you were to use only top-level functions with a namespace (import 'libsodium.dart' as libsodium).
Dart does not have any way to implicitly run code. No code runs before main, and all code running after main does so because it was invoked directly or indirectly from the main method. So, no.
If you need something initialized, there is a number of options.
You can use a lazily initialized static variable:
var _initialState = _init();
int doSomething(arguments) {
_initialState;
do the something.
}
The reading of _initialState will ensure that init is invoked the first time
it's needed, and not after that. You can even store things in the state for
later use.
The singleton implementation object suggested by #jamesdlin. It basically does the
same thing, then puts the methods on the object instead of being static.
Another variant is to do exactly that, but with a private instance, and have the
public top-level functions forward to the singleton object. Then you get the
procedural API and still ensures that the state object is initialized.
(This may be better for testing, allowing you to have multiple state objects alive
at the same time).
Require people to call init.

is there a better way to call overridden behavior functions than super.test()?

I have abstracted a bunch of code to behaviors, and now when i do:
class B extends A with behave {
B():super(){}
}
class A extends PolymerElement{
A(){}
}
abstract class behave {
test(){ print("Test"); }
}
So what I have been trying to do is create a workflow without having to append references to this new function test
As of right now, if you implement test in A or B, it will override the behavior I had created. But I was hoping to append more to it, something similar to:
class B extends A with behave {
B():super(){}
test():super.test(){}
}
and this would do something like call the parent test. Now when looking this, i would say, this would make sense if the behavior was in the parent. So lets test that out.
abstract class behave { ... }
class A extends behave { ... }
class B extends A {
test(){
super.test();
}
}
This would work and execute what I was wanting to do... Why cant i reference it in the instantiation? test():super.test(){ ... } It seems that doing as just stated will error as a constructor error.
Now what if we put it back to my original design, as behave being with B
abstract class behave { ... }
class A { ... }
class B extends A with behave {
test(){
super.test();
print("Foo");
}
}
now here it seems to work as expected, requiring us to create a super reference to this behavior.
Is there an idea of using : for referencing a parent function call, or is this only ever used for constructors? I would say, yes it is only used for constructors for now, but why not append additional functionality. If i wanted to create a series of functions in the behavior which mimic the child implementation, I should either run super.test() either at the top of bottom of the function depending on the order required to function?
Is there something I am missing in dart when reading the docs, or is this how it is suppose to work for the time being?
I doubt that foo() : super.foo() syntax will be added to the language. The : for constructor initializers is useful because the initializers can be analyzed at compile time, which make it simple to verify that final fields are set for instance. The : syntax in a function would just be syntactic sugar for putting that function call at the beginning of the function, which doesn't seem to add much value.
By the way, you can add #mustCallSuper to your the test() function. This will add a check to the linter that all methods that override test() must call super.test().

Dart Polymer 1.0 Behavior - method not found & getters required

I wanted to write a simple behavior in Dart to be used by a custom element.
#behavior
abstract class AlignmentBehavior implements PolymerBase {
#Property()
bool alignTop = false;
// more properties ...
ready() {
updateAlignment();
}
#reflectable
updateAlignment([_,__]) {
// reference to the element the Behavior is attached to.
// 1) Is that the correct way?
var ele = Polymer.dom(root);
// We need to inherit from PolymerBase to access set(...)
// 2) Is that the correct way?
set('alignTop', aTop);
// .. to more stuff
}
}
My first two questions are already written in the code. How do I access the element the behavior is attached to? What's the proper way of doing this? I currently use Polymer.dom(root) but I don't know if that even works since I have some runtime errors which I am going to explain later in this post. What is the official way of accessing the underlying element? Is it using the JsObject? Is it calling a Behavior function from the parent PolymerElement and pass this, or should you not access it at all?
Another question is whether I have to inherit from PolymerBase or not. The Behavior example at the Github wiki doesn't do so, but in order to access methods such as set to modify a #Property I have to inherit from it. What's the proper way of doing so?
My last two questions are about errors I get. One error asks me to implement getters and setters for my properties, such as adding a getter and setter for alignTop.
And last but not least, I cannot invoke updateAlignment() from my custom element. It says Class 'MainApp' has no instance method 'updateAlignment'.
1)
var ele = Polymer.dom(root);
If you want to access the DOM of the element, this fine.
Just root gives you the same AFAIK.
If you want to access the elements class instance, there is nothing to do. It's this but that is implicit in Dart anyway.
You can only access what is known in the mixin. To make "things" known to the mixin you can create an interface class.
abstract class MyComponentInterface {
void someFunction();
int someField;
String get someValue;
set someValue(String value);
...
}
Then implement the interface in the mixin and the element class and you have a shared contract.
abstract class AlignmentBehavior implements MyComponentInterface, PolymerBase {
The mixin can now access the members because the implementsMyComponentInterface` claims they will exist and
class MyComponent extends PolymerElement with AlignmentBehavior {
will force you to implement it to fulfill the contract of the mixin.
2) looks fine
3)
Another question is whether I have to inherit from PolymerBase or not.
Is basically the same as 1) Any Polymer element in Dart has to extend PolymerBase. To be able to access the members of PolymerBase from within the mixin it has to implement it as well. This doesn't result in any limitations because the classes that the mixin will be applied to, will fulfill that contract anyway.
If you don't need to access any members provided by PolymerBase there is no need to implement it.

Dynamically extend a Class

I wonder if there is the possibility to dynamically extend a class, I'm new to Dart and I'm looking for something like this (please forget about the ${whatever} is just for illustration purposes):
class MyClass extends ${otherClass}
and let's say I'm trying to instantiate it from another function:
var myDinamic = new myClass<otherClass>
Hope this makes sense and thanks in advance!
In short: No.
Dart requires all classes to have a single superclass. What you are asking for is having a single class that changes its superclass per instance. That's not really a single class - it's impossible to say which members that class has because it is really a different class for choice of superclass.
That a class extends another class can only be defined statically but not at runtime. The closest to that is probably configuring types with generic type arguments.
See also
- https://www.dartlang.org/docs/dart-up-and-running/ch02.html#generics
- http://blog.sethladd.com/2012/01/generics-in-dart-or-why-javascript.html
abstract class SomeInterface {}
class A implements SomeInterface {}
class B implements SomeInterface {}
class C<T extends SomeInterface> {
T doSomething(T arg) { return arg; }
}
main() {
new C<A>();
new C<B>();
// does NOT work
// var t = A;
// new C<t>();
}
but type arguments also need to defined statically. You can't use a variable as generic type argument.

Can I override a binding in dagger?

If I have a default impl of a class, and it does define #Inject constructor, that's great. The system picks it up.
If one app wants to override that default impl with a subclass, I can define an #Provides in its module and call "new" on that subclass in my own code, and dagger uses that impl instead (from what I can tell so far, this works).
However, if I want dagger to instantiate that subclass, it there a way to do it without declaring "override=true" in the #Module? I like not having the override=true so that all the duplicate checks at build time give me appropriate warnings.
One way to do it, of course, it to force all apps to declare the #Provides directly. That just adds to the bloat.
I've used GIN (Guice for GWT) before, and you can define a binding to the class you want by a .class reference, but I don't see anything similar in dagger.
Right now, there is no way to have a "default binding" which you can freely override, without using the "overrides" attribute (which was intended more for testing than this.) We are considering how to do default bindings.
You might consider using a set binding to do this, by having something like along these lines:
#Module(...)
class MyModule {
#Qualifier #interface OverridableFoo { }
#Provides(type=SET_VALUES) #OverridableFoo Set<Foo> provideOverriddenFoo() {
return new HashSet<Foo>(); // Empty set to ensure the Set is initialized.
}
#Provides Foo provideFoo(#OverridableFoo Set<Foo> Foo overriddenFoo) {
switch (overriddenFoo.size()) {
case 0: return new DefaultFooImpl();
case 1: return overriddenFoo.iterator().next();
default: throw new IllegalStateException("More than one overridden Foo Provided.");
}
}
}
Then, when you want to override, you simply include this:
#Module(...)
class MyModule {
#Provides(type=SET_VALUE) #OverridableFoo Foo provideBetterFoo() {
return new MyAwesomeFoo();
}
}
This is not a great way to go, as it moves what should be a compile-time error to run-time, but as a stop-gap while we attempt to decide how to handle default bindings, I think it is workable.

Resources