I was wondering if there is a way how to perform actions in a function after it returning a value.
i.e there is a method which returns a string. Now after the string is returned I want the method to perform another action like checking whether a condition is met so it can send out a notification or something else. Is that somehow possible?
The thing is that I am using a framework called core plot to add some plots to my application. Unfortunately this framework does not have a didFinishAddingPlot method. So I have to manually program a mechanism which notifies me whenever the plot finished plotting. When the addPlot method is called another method is called which goes through an array of values and returns a value for a specific index to plot. My idea was to put in a "if (condition)" block to check if the index is equal to the count of my values array so I know that it is now fetching the last value. However it first needs to return the value before sending a message that it finished plotting. Otherwise the last value won't get passed.
As soon as a function hits a return statement the function stops running. You would need to perform whatever other action you want to do before you return.
So, you want to return a value from your function or method, which by definition returns control (as well as your answer) to the call site. On the face of it, it's not possible; you've returned control, so you're done.
But you could spawn a new Thread during your method execution, to (for example) perform some cleanup tasks later on.
Since you tagged the question as Cocoa, check out Apple's Threaded Programming Guide, which will teach you about NSThread, POSIX threads, and more.
Related
I have an application where users can take part of puzzle solving events. I have an API endpoint /events/{id} that is used to get data associated to a certain event.
Based on whether the event has ended, the response will differ:
If the event has ended, the endpoint will return event name, participants, scores etc. with status code 200
If the event has not ended, the endpoint will return event name, start time, end time, puzzles etc. with status code 200.
On the client-side, what is the best way to distinguish these two responses from each other to decide which page to display, results page or event page? Is this a good way to accomplish my goal?
Some might answer that I should already know on the client-side whether the event has ended and then query for data accordingly. But what if user uses the address bar to navigate to an event? Then I will have no data to know, whether it truly has ended. I wouldn't like to first make an API call to know that it has (not) ended and then make another one for results/puzzles.
pass a boolean isFinished and return it inside of response object. If your response object is already defined, create a wrapper that has the previous response dto and a boolean flag.
Also we did use a solution like this in one of our projects at work for a big company so I would say it is somewhat industry accepted way of doing it.
I'm using gin-gonic as HTTP handler. I want to prerender some graphical resources after my users make POST request. For this, I put a middleware that assign a function (with a timer inside) to a map[string]func() and call this function directly after assignation.
The problem is, when the user make two subsequent request, the function is called twice.
Is there any way to clear function ref and/or his currently running call like a clearInterval or clearTimeout in Javascript ?
Thanks
No; whatever function you've scheduled to run as a goroutine needs to either return or call runtime.Goexit.
If you're looking for a way to build cancellation into your worker, Go provides a primitive to handle that, which is already part of any HTTP request - contexts. Check out these articles from the Go blog:
Concurrency Patterns: Context
Pipelines and cancellation
I suppose your rendering function is calling into a library, so you don't have control over the code where the bulk of the time is spent. If you do have such control, just pass a channel into the goroutine, periodically check if the channel is closed, and just return from the goroutine if that happens.
But actually I would recommend a different, and simpler, solution: keep track (in a map) of the file names (or hashes) of the files that are currently being processed, and check that map before launching a second one.
How would I go about creating a simple Scheduler that say, delays every item by a second? I want to use it for an Observable, and yes, I know that can be done in multiple other ways, I jsut want to accomplish it using a custom Scheduler.
There's some related tutorial here: http://codebetter.com/matthewpodwysocki/2010/05/12/introduction-to-the-reactive-extensions-for-javascript-custom-schedulers/ but it is quite outdated and the API looks very different now.
The current docs are not very usefuleither, but I guess I should be using Rx.Scheduler.prototype.schedulePeriodic, although I don't know what the action parameter should be.
To create a new scheduler from the base scheduler you should have a look at scheduler.js. Essentially you need to understand how to do 4 things and you will automatically get all the periodic, recursive, exception handling extensions for free.
The function signature of Scheduler is
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute){}
To break it down:
now - A function that represents the schedulers notion of time, at any point when this is called it should return what the scheduler thinks now is. The default is to simply return new Date()
schedule - A function called when the action should be executed as soon as possible This function has the signature
function scheduleNow(state, action) {}
where action will have the signature
function action(scheduler, state) {}
It is used to schedule immediate actions on the scheduler. Immediate will have different meanings depending on your scheduler, however, for most cases (immediateScheduler aside) you will want that to occur in the next tick, whatever that means to your scheduler. You can have a look at the defaultScheduler, which does a little work to figure out what the best method would be in the environment (setImmediate is the first choice). In your case, since immediate will really mean "one second from now", you could probably just route it to scheduleRelative with this.scheduleRelativeWithState(state, 1000, action)
scheduleRelative This is called when the action should occur sometime in the future relative to now:
function scheduleRelative(state, dueTime, action) {}
Again this will likely use setTimeout with dueTime as the time parameter.
scheduleAbsolute This is probably the easiest to implement, it has the same signature as scheduleRelative, however instead of taking a time relative to now it is taking an absolute time irrespective of now (usually a Date object), to convert it you really just need to subtract now from it and pass it into this.scheduleWithRelativeAndState (see I told you you'll get free stuff).
In all cases the 3 schedule methods return a Disposable, this is used for best effort cancellation of the action. In the case of setTimeout this would be clearing the timeout using the returned id.
To finally answer your question, if you wanted to delay everything by 1 second the best way will probably be to apply a shift in scheduleRelative adding 1 second/1000 milliseconds to each scheduled event.
Will ParseObject.saveEventually(SaveCallback cb) populate the parse object's object id before calling the callback's "done" method? There is nothing about this in the documentation and although I could experiment with trail/error, it wouldn't guarantee anything in all cases or in the future.
My usecase is to minimize web calls as much as possible and so I'd much rather grab the object ID on completion instead of having to call back to parse on completion to pull down the data if it's already available.
I'm currently developing a multiplayer cardgame for android, with libgdx as the game engine. My question is more generel tho.
I'm not sure whats the best practice for handling callbacks in this architecture. My controller is a big statemachine, that checks inputs over and over while beeing called from the render() method of the gameengine.
I have two main callbacks, userinput from the gui, and network callbacks from the android google play services part.
Currently these callback methode/ inputListeners just set member variables, which are check by getter methods from the controller/statemachine, for example i call this from the controller over and over, check if its != null and proceed if it is.
#Override
public Boolean allPlayersConnected() {
Boolean allConnected = null;
if (startGame != null) {
allConnected = startGame;
startGame = null;
}
return allConnected;
}
The startGame "flag" beeing set by callbacks from the google play services api.
I dont know if this is good practice, doesnt look like.
I could call controller methods from the google play services callbacks that set a controller member variable, and check this in each render loop, but thats just moving the variable.
I could also design the controller as an observer of those events, but what am i going to do in the update method inside the controller thats beeing called if an event happens. i dont think i want change stats in these, even if i can access the currrent state. Im spreading state code all over the place with this, some in different parts of a huge update method and some in the actual state machine code. Just setting a member variable in the update method is quite similar to the think i did above.
Another thing would be, to directly change controller state from the callback methods. That would be less code, less variables and a little faster, but i think i'd destroy the MVP concept, cause i take away the control from the controller and let i.e. the gui change the state of the controller.
Any input on this ?
Edit:
The more i think about it, the more i think a combination of observer and command pattern is the way to go.
So i could indeed cut big part of the current state machine and pack it into the observer update() method. Instead of sending the commands through a big command enum, i could create command object with the information available, and pass them to the observer(controller), where i check the command as viable, and call the execute with the information needed to be excecuted, eg the model interface.
First, I think whether your commands are enums or command objects is independent of the main problem here -- which is how to connect user and network input to state management.
The most common game architecture I've seen is an update loop that checks input, iterates the game simulation, and then renders a frame. In the MVC world, this structure just synchronizes those steps; you still have an encapsulated view and data model, with the controller (the game loop) serving as a a bridge between those two worlds.
Input, whether from the local user or one over the net, is generally treated as a request to modify game state. That is, the controller (as the first part of its loop) reads in pending input messages and processes them, modifying state as it goes. This way, the code that changes state is in one place: that controller. You are right, spreading state-modification code throughout the app is a bad practice; basically, it's not MVC.
In other words, all of your callbacks should convert the input to commands and stick them into a queue. You don't want to synchronize the controller -- whose job it is to modify state -- with those input callbacks. You have no idea when input will occur relative to the game loop, so it's best to decouple them. Serializing input processing with game simulation should also make your logic simpler.
You have some choice in how to connect the callbacks to the controller; a shared queue (where one side writes into it and the other reads out from it) is a strong pattern and easy to make thread-safe.