Hey guys i am a new guy trying to figure out some method that's confusing
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
This is a piece of code i found and it was used like
$("input").keyup(function() {
delay(function(){
alert('works');
}, 1000 );
});
I know the above code works as ive tested it but i dont understand what exactly does (function(){ mean,and how does callback have the
function(){alert('works');}
as the parameter when no parameter was accepted before..!
thanks guys
a function is just a way to wrap many lines of code together.
You can have it anonymous and execute instantly:
(function (){ alert("I'm working!");})();
You can then give it a name like:
function myFunction(){ alert("I'm working!");}
and you can call it with:
myFunction();
you could do
$("input").keyup(function() {
delay( myFunction, 1000 );
});
and it would run myFunction after 1000ms once a key is lifted up when typing in the input.
Assign to delay the invocation of the anonymous function that closes over the timer variable and returns a second anonymous function which takes two parameters, callback and ms (therefore, the type of delay is also a function of two arguments) which clears the handle associated with the timer variable, then invokes the callback. Useful if you will have something that calls delay faster than the timeout, and you only want to respond to the most recent call.
We could do this to make it (slightly) more clear:
//define the closure
var closure = function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
};
//invoke the closure to return the function that we will actually use as delay
var delay = closure();
delay is set to a function which is returned by the immediately executing function (function(){ …return function()... })(); The function immediately executing one, also creates the closure around the timer variable.
the (function(){ … })(); is not exactly a window.ready. Rather it executes wherever it is put. Notice the () at the end. And it returns another function which is hold inside variable delay.
Then on input key up on an an alert is displayed after 1 second, however to prevent the alert getting displayed several times if the up key is pressed several times within 1 second the closure around timer is used to cancel the invocation of previous timer using clearTimeout
$("input").keyup(function() {
delay(function(){
alert('works');
}, 1000 );
});
//delay takes 2 params callback and ms
//ms:1000
//set the callback as:
function(){
alert('works');
}
now delay invokes following code that has already created closure around timer var.
function(callback, ms){
clearTimeout (timer); //attempts to cancels previous timer event that would invoke alert callback
timer = setTimeout(callback, ms); //call back the above set callback after ms value i.e. 1000 milli seconds
};
Related
I have a problem that I still can't solve and it just doesn't want to work. Basically I have to convert a function into a composable.
In the old function I launched a Coroutine and at the result, I changed context and then continued with my processes. In compose I don't understand how I have to "change context" in order to continue.
Old code:
fun getMyView( activity: Activity
) {
backgroundCoroutineScope.launch {
//some stuff here
withContext(coroutineContext) {
startSearchView(
activity
)
}
}
}
New not working code:
#Composable
fun getMyView( content: #Composable() () -> Unit) {
LaunchedEffect(key1 = Unit) {
//some stuff here like old funciont
//here I don't know how to change context, wait the end and go ahead. startSearchViewis a composable function too
// i want to use it to populate my screen
startSearchView(
content
)
}
}
How can I solve it? Thanks
Seems like you are trying to asynchronously "create" composable function, but UI emitting doesn't work this way. Like #PylypDukhov suggested, you should keep a mutable state holding nullable result of your async action. After loading the data set this state. Then in composable just do something like:
if (data != null) {
SearchComposable(data)
}
This way the composable will be emitted after the data is loaded
I'm wondering if there is a way in RxSwift to observe value of stored variable property. Eg. in following example:
var updatedValue: Int = 0
var observedValue: Observable<Int> {
return Observable.create({ (observer) -> Disposable in
observer.onNext(updatedValue)
return Disposables.create()
})
}
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
updatedValue = updatedValue + 1;
}
let myObservable = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.publish()
myObservable.connect()
myObservable
.withLatestFrom(observedValue)
.subscribe { (event) in
print(event)
}
We have variable property updatedValue and hot observable myObservable. We also increment value of updatedValue in Timer.scheduledTimer....
Flow here is pretty straight forward. When we subscribe, observedValue gets called, we get onNext from observedValue and then Disposables.create(). Then we print event onNext(0).
As myObservable is based on Observable.interval, same withLatestFrom value gets printed in onNext every second.
Question: Is there a way to print last value of updatedValue every time myObservable emits new event? So instead of 0,0,0... we get 0,1,2...
I'm aware that updatedValue could be declared as BehaviorRelay.
I'm also aware that we could use .map { } to capture self.updatedValue.
But I'm wondering if there is any way to create a Observable wrapper around standard variable property so it calls onNext with most recent value every time trigger sequence sends an event? Without capturing self or changing declaration on updatedValue.
Thanks for any comments and ideas!
RxCocoa has a handy wrapper around KVO. You should be able to use it from .rx extension on NSObject subclasses.
For your issue, I guess you can do something like:
let updatedValueObservable = self.rx.observe(Int.self, "updatedValue")
But I'm wondering if there is any way to create a Observable wrapper around standard variable property so it calls onNext with most recent value every time trigger sequence sends an event? Without capturing self or changing declaration on updatedValue.
The correct answer is, no. There is no way to do anything to updatedValue without involving self. One way of doing it would be with Observable<Int>.interval(1, scheduler: MainScheduler.instance).compactMap { [weak self] _ in self?.updatedValue }.distinctUntilChanged() (Your use of publish and connect is odd and unnecessary,) but that involves self.
Since your property is a value type, the only way to access it is through self, even if Rx wasn't involved at all.
I have the following async recursive code:
func syncData() {
dal.getList(...) { [unowned self] list, error in
if let objects = list {
if oneTime {
oneTime = false
syncOtherStuffNow()
}
syncData() // recurse until all data synced
} else if let error = error {... }
func syncOtherStuffNow() { } // with its own recursion
My understanding is that the recursion will build the call stack until all the function calls complete, at which point they will all unwind and free up the heap.
I also want to trigger another function (syncOtherStuffNow) from within the closure. But don't want to bind it to the closure with a strong reference waiting for it's return (even though it's async too).
How can I essentially trigger the syncOtherStuffNow() selector to run, and not affect the current closure with hanging on to its return call?
I thought of using Notifications, but that seems overkill given the two functions are in the same class.
Since dal.getList() takes a callback I guess it is asynchronous and so the the first syncData starts the async call and then returns immediately which lets syncData() return.
If syncOtherStuffNow() is async it will return immediately and so dataSync() will not wait on it finishing its job and so continue with its execution to the end.
You can test whether sth builds a callstack by putting a breakpoint on every recursion and look on the callstack how many calls of the same function are ontop.
What I do is recurse with asyncAfter, which unwinds the call stack.
I'm trying to write a function on a MovieClip, and call it from the root clip. What works fine in ActionScript 3 doesn't seem to be working properly in ActionScript 2.
Frame 1 of the _root MovieClip:
var newMovieClip:MovieClip = _root.attachMovie('Notification', id, 0);
newMovieClip.SetNotificationText("Test text");
Frame 1 of the Notification MovieClip:
function SetNotificationText(inputText : String){
notificationText.text = inputText;
}
The result is that the MovieClip is created but the text is not changed.
Am I doing this wrong?
To add functions to a MovieClip in AS2, you need to use one of these methods:
Add the method to the prototype of MovieClip:
MovieClip.prototype.SetNotificationText = function(inputText:String):Void
{
if(this["notificationText"] !== undefined)
{
// If we're going to use the prototype, at least do some checks
// to make sure the caller MovieClip has the text field we expect.
this.notificationText.text = inputText;
}
}
newMovieClip.SetNotificationText("Test text");
Make the MovieClip and argument of the function:
function SetNotificationText(mc:MovieClip, inputText:String):Void
{
mc.notificationText.text = inputText;
}
SetNotificationText(newMovieClip, "Test text");
Add the method directly to the newly created MovieClip:
var newMovieClip:MovieClip = _root.attachMovie('Notification', id, 0);
newMovieClip.SetNotificationText(inputText:String):Void
{
notificationText.text = inputText;
}
newMovieClip.SetNotificationText("Test text");
Option 2 is best overall - it's the cleanest and avoids overhead of creating a new function for every new MovieClip. It also avoids messing around with the prototype, which at best should be used to add generic methods, like a removeItem() method on Array.
I have used completionHandler in my Application as follows
fun getDetails(completionHandler: (variable: AnyObject) -() )
{
// Some work
completionHandler(variable)
}
getDetails
{
variable in
print(variable)
}
My question is what is the sequence of function calls for this execution to happen?
So the answer is when a function (say A) which has function(say B) as a parameter is called, the called function (A) execution begins. As soon as the function in parameter(function B) is called the flow goes to the point where function (A) was called. Execution of that code begins and after the execution of it, the left over part of the function(A) is executed.
In the above example when getDetails is called, the execution for that function begins but when completionHandler is called the flow jumps to the { part of getDetails, only after this is finished it comes back and starts executing after the completionHanldler() is called.