Why doesn't the late Timer.periodic work in flutter & dart? - dart

This timer does not work.
Why?
What is late doing?
import 'dart:async';
void main() => A();
class A {
final a = 10;
late final Timer timer = Timer.periodic(
Duration(seconds: 1),
(timer) {
print(a);
},
);
}

late have multiple meanings in Dart but if used when declaring value of the variable right away, it means the variable are first assigned its value when you access the variable the first time.
So your code are not doing anything since you, at no point, are trying to read the timer variable.
You can read more about this in the official documentation: https://dart.dev/null-safety/understanding-null-safety#lazy-initialization

You are trying to do a Lazy initialization for the timer, but there is just a little point you are missing that causes the current behavior.
As the official docs states:
When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed.
So by creating a new object of class A by calling it is constructor, this will not initialize the timer, it would be initialized once it is accessed, and that is the meaning of Lazy initialization.
So if we accessed the timer property inside the constructed object, the intended behavior will occur and the timer callback would run as you want.
Try this one:
void main(){
final aObject = A();
print(aObject.timer);
}
I have created the example in DartPad to let you easily test and play around with it, access it via this link.

late modifier means “enforce this variable’s constraints at runtime instead of at compile time”.
You can check lazy-initialization.
When you do this, the initializer becomes lazy. Instead of running it as soon as the instance is constructed, it is deferred and run lazily the first time the field is accessed. In other words, it works exactly like an initializer on a top-level variable or static field. This can be handy when the initialization expression is costly and may not be needed.
Find more late keyword with declaration
And doing void main() => A(); just creating an instace of A.
If you like to run timer, do it like
void main() {
final a = A();
a.timer;
}

Related

Why does setState take a closure?

What's the benefit of having setState() accept a function just to immediately call it and then request rebuild? In particular, what's the advantage over having users explicitly call a "rebuild" type function?
When Flutter had a "markNeedsBuild" function, developers ended up just sort of calling it at random times. When the syntax switched to setState(() { ... }), developers were much more likely to use the API correctly. They are functionally equivalent from the machine's point of view, but they seem to evoke different code from developers.
If you follow the convention of only mutating member variables inside a setState closure, you'll avoid a situation you're refactoring some code and accidentally remove the call to setState, or call setState unnecessarily. And if your State is unmounted, Flutter can fail an assertion so you know something is wrong as soon as you begin trying to mutate members, instead of at the end.
Eventually there will probably be an analyzer warning enforcing that setState is always called when mutating members of a State, so any member variable mutation that happens outside of initState or a setState callback will be flagged as suspect.
If you're just getting started with state in Flutter, check out the Flutter widgets tour. I've found that a lot of cases where I was calling setState can be handled more elegantly with FutureBuilder, StreamBuilder, AnimatedWidget, or AnimatedBuilder, so don't forget to consider those alternatives if you find yourself calling setState a lot.
Adam Barth and Yaroslav Volovich contributed to this question/answer.
To complete Colin's answer, it also ensures that you call setState at the right moment when dealing with asynchronous function.
Mutating your state outside of the callback can lead to an easy mistake:
function() async {
setState(() {});
myState = await future;
}
This causes a problem because if your future doesn't finish synchronously, the build method will be called before the state is mutated.
By using the callback you are forced to do the following:
function() async {
final value = await future;
setState(() {
myState = value;
});
}
This time, it doesn't cause problems because the future is awaited before the setState.
Can't I make an async callback and still have the issue?
No. Because setState method internally check that the callback does not return a future. And if it does, it will throw.
So the following is impossible:
setState(() async {
myState = await future;
});

Differrence between closure and function as argument in swift

I have almost 4 years of experience with Objective C and a newbie in swift. Am trying to understand the concept of swift from the perspective of Objective C. So if I am wrong please guide me through :)
In objective c, we have blocks (chunck of code which can be executed later asynchronously) which made absolutely perfect sense. But in swift now we can pass a function as a parameter to another function, which can be executed later, and then we have closure as well.
As per Apple "functions are special cases of clauses."
As per O'Reilly "when a function is passed around as a value, it carries along its internal references to external variables. That is what makes a function a closure."
So I tried a little bit to understand the same :)
Here is my closure
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a ni
let tempNumber : Int = 5
let numbers = [1,2,3,4,5]
print (numbers.map({ $0 - tempNumber}))
}
The variable tempNumber is declared even before the closure was declared, yet closure has the access to the variable. Now rather then a map, I tried using a custom class passed closure as a parameter and tried executing the same code :) Though now closure is getting executed in differrent scope, it still has the access to tempNumber.
I concluded : closures have an access to the variables and methods which are declared in the same scope as closure it self, though it gets execcuted in differrent scope.
Now rather then passing closure as paramter, tried passing function as a parameter,
class test {
func testFunctionAsParameter(testMethod : (Int) -> Int){
let seconds = 4.0
let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.callLater(testMethod)
})
}
func callLater(testMethod : (Int) -> Int) -> Int {
return testMethod(100)
}
}
In a differrent class I created an instance of Test and used it as follow
/* in differrent class */
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a ni
let tempAge : Int = 5
func test2(val : Int) -> Int {
return val - tempAge;
}
let testObj = test();
print(testObj.testFunctionAsParameter(test2))
}
Declared a class called test, which has a method called testFunctionAsParameter which in turn calls another method called callLater and finally this method executes the passed function :)
Now all these circus, just to ensure that passed method gets executed in differrent scope :)
When I executed the above code :) I was shocked to see that even though function passed as a parameter finally gets executed in different scope, still has the access to the variables testNumber that was declared at the same scope as the method declaration :)
I concluded : O'Reilly's statement "when a function is passed around as a value, it carries along its internal references to external variables." was bang on :)
Now my doubt is apple says functions are special cases of clauses. I thought special case must be something to do with scope :) But to my surprise code shows that both closure and function have access to variables in external scope !!!!
Other then, syntax differrence how closure is differrent from function passed as argument ??? Now there must be some differrence internally, otherwise Apple wouldn't have spent so much time in designing it :)
If not scope?? then what else is different in closure and function ?? O'Reilly states "when a function is passed around as a value, it carries along its internal references to external variables. That is what makes a function a closure." so what is it trying to point out ? that closure wont carry references to external variables ? Now they can't be wrong either, are they?
I am going mad with two conflicting statements from Apple and O'Reilly :( Please help, am I understanding something wrong ?? Please help me understand the difference.
In swift there really isn't any difference between functions and closures. A closure is an anonymous function (A function with no name.) That's about it, other than the syntax differences you noted.
In Objective-C functions and blocks/closures ARE different.
Based on your post, it looks like you have a pretty full understanding on the topic and you may just be getting lost in the semantics. It basically boils down to:
1. a closure is a closure
2. a function is a closure with a name
Here's a post with more details. But again, it's mostly a discussion of semantics. The "answer" is very simple.
What is the difference between functions and closures?

Force garbage collection of JavaScriptCore virtual machine on iOS

Is there any way to force iOS (or Mac OS) JavaScriptCore VM garbage collector to run? I need it only to test for memory leaks, so private API would be fine.
Use following function from JSBase.h:
/*!
#function JSGarbageCollect
#abstract Performs a JavaScript garbage collection.
#param ctx The execution context to use.
#discussion JavaScript values that are on the machine stack, in a register,
protected by JSValueProtect, set as the global object of an execution context,
or reachable from any such value will not be collected.
During JavaScript execution, you are not required to call this function; the
JavaScript engine will garbage collect as needed. JavaScript values created
within a context group are automatically destroyed when the last reference
to the context group is released.
*/
JS_EXPORT void JSGarbageCollect(JSContextRef ctx);
You can obtain JSContextRef from your JSContext, using JSGlobalContextRef readonly property.
Update
I've found next change in WebKit - bugs.webkit.org/show_bug.cgi?id=84476:
JSGarbageCollect should not synchronously call collectAllGarbage().
Instead, it should notify the GCActivityCallback that it has abandoned
an object graph, which will set the timer to run at some point in the
future that JSC can decide according to its own policies.
This explains why previous solution doesn't work as expected.
Digging deeper into WebKit sources, I found another interesting approach. Please, try following code:
JS_EXPORT void JSSynchronousGarbageCollectForDebugging(JSContextRef ctx);
#interface JSContext (GarbageCollection)
-(void)garbageCollect {
JSSynchronousGarbageCollectForDebugging(self.JSGlobalContextRef);
}
#end
Simply call garbageCollect method on your JSContext instance after that. I've tried it locally on iOS and it seems to work.

How to dispatch an event when a object is ready on Dart?

I'm experimenting some WebGL in Dart and I had created a class that loads shaders from separate files and I would like to throw an event (function) when the object is ready, so I can continue my application knowing that my shaders are properly loaded. Do someone knows an easy way to do this?
One approach is to use a Future pattern to accomplish this:
Future<SomeType> initMyObject(){
final c = new Completer();
// Do my object init stuff
// and when it is complete:
c.complete(instanceOfSomeType);
// Return the Future object to any subscribers.
return c.future;
}
Then elsewhere you can get notified like so:
initMyObject().then((SomeType t){
//executes when future completes
});

where to use delegates in c#

i have better understanding in how the delegates and events work , but i dont know
where it is of full use when we develop a Library or a application.
thanks
Delegates are significant as they are needed to work with events (not just this).
Lets say we have a winform F1..A function within F1 opens another form F2. and if a function within F1 has to be executed based on users activity on F2 we'll definitely have to make use of delegates and events.
1)A delegate type has to be declared (Signature has to match with eventhandler which you are planning to attach)
2)F2 will need to have an event as class member of delegate type
3)Just as you create an instance of F2 in F1 , attach the event handler (using += )
Delegates are similar to function pointers of C/C++ but are of class type and not primitive type.
The basic use of delegates is to perform some call back or asynchronous methods or to pass different methods at runtime. (substituting the logic)
Example for performing asynchronous call back. It is more appropriate when you have multiple threads running.
public class MyClass
{
public delegate void CallBackDelegate(int result);
public void CallsBack(CallBackDelegate callBack)
{
// your code here - do something useful
callBack(result);
}
}
public class DelegateExample
{
// some more useful code here
void ExampleMethod()
{
// more code
MyClass myclass = new MyClass();
myclass.CallsBack(CallMeBack);
// Continue with your work and don't wait for call back.
}
void CallMeBack(int result)
{
// do something useful
}
}
This is a very general question, but a typical use of delegates and events would be in a GUI library. For example, you could set up events to fire when a button is clicked on an application, or when a value is changed in a field, and a developer could then use delegates to specify one of their own functions to be called in response to that button click, or to perform validation on the changed data.

Resources