How to call Async method from non-Async method with method hook? - asynchronous

Scenario:
1. I'll get call from UI to my Web Api.
2. My business logic process some data and create two lists.
3. Out of these two list one list data has to be return to the UI back and remaining list data again processed by another component which returns me the result on which i again has some business logic to be executed.
What will be the best practices and how will it be implemented?
Please provide the code snippets.

Related

Is Reactor's FlatMap Asynchronous?

I'm new to reactive programming and I'm using reactor through micronaut framework and kotlin. I'm trying to understand the advantages of reactive programming and how we implement it using Map and FlatMap through Mono and Flux.
I understand the non-blocking aspect of reactive programming but I'm confused if the operation on the data stream is actually asynchronous.
I've been reading about FlatMap and understand that they asynchronously produce inner streams and then merge these streams to another Flux without maintaining the order. The many diagrams I've seen all make it easier to understand but I have some basic questions when it comes down to actual use-cases.
Example:
fun updateDetials() {
itemDetailsCrudRepository.getItems()
.flatMap {
customerRepository.save(someTransferObject.toEntity(it))
}
}
In the above example assume itemDetailsCrudRepository.getItems() returns a Flux of a particular Entity. The flatMap operation has to save each of the items in the flux to another table. customerRepository.save() will save the item from the flux and we get the required entity through an instance of a data class someTransferObject.
Now, let's say the getItems() query returned 10 items and we need to save 10 rows in the new table. Is the flatMap operation(the operation of saving these items into the new table) applied to each item of the flux one at a time(synchronously) or does all the save happen at once asynchronously?
One thing I read was if subscribeOn(Scheduler.parallel()) is not applied then the flatMap operation is applied to each item in the flux one at a time(synchronously). Is this information right?
Please do correct me if my basic knowledge itself is incorrect.

Reason to integrate Spring Web-flow with Spring MVC

Why(In what scenarios) do we need to integrate Spring Webflow with Spring MVC? Both these frameworks are used to create web-app and I do not see any point why we would integrate them. I would appreciate if someone could clarify me about it.
This is really late but I don't see a satisfactory answer to this question and would like to share an approach I had tried in a recent project which I feel is better than the spring web flow approach which is strictly tied down to spring views and unnecessarily adds to the already existing xml load . I created a SPA(Single Page Application) using angular js with Spring MVC. In angular js I did not use routers or state, rather I created a div within the controller like below
On the server side to capture all possible transitions from one frame(I am referring to a particular screen in the SPA) to another I created a tree of rules using MVEL . So in the database I had a structure which stored a tree of rules for every frame . The data in the MVEL expressions were being set by the various services each action invoked. Thus on any action the following steps were followed.
1) Validate the action.
2) Invoke various services.
3) Capture the data from these services and merge it with the existing data of the user.
4) Feed this captured data into collection of rules for each frame along with the details of the current frame.
5) Run the rules of the tree w.r.t to current frame and fetch its output.
6) If there is only one transition then that is the final transition. If there are 2 transitions and one is default then ignore the default transition and use the other transition.
7) Return the template name of the transition to the angular controller and set the value of the page variable in the scope of the controller.
Using this approach all my services had to do was store data in different data fields w.r.t a particular action. All the complex if-else conditions for Web Flows or any complex process definitions(like the one defined in Spring-Web Flow) were not required. The MVEL rule engine managed all that and since it was all in the database it could be changed without needing a server re-start.
I believe this generic approach with MVEL is a flexible approach which comprehensively handles the problem of a convoluted flow without making the application code a mess or adding additional unnecessary xml files.
We combine both. Web Flow for the multi-step activities, where it doesn't make sense to jump into the middle of a process, and plain-MVC Controllers for the single-step activities. Things you might bookmark individually.
For example, an appointment-scheduling application, "find my appointment" might be a single Controller that accepts identifying information. "Make a new appointment" is a flow, with multiple steps of selecting a location, date, time, confirm the appointment, etc.
If your application have complex Flow pages, events which need to be defined as Finite state machine then use Webflow. It would be justified to use webflow for website where you buy Insurance, Flight Tickets. Web Flow conditions are like:
There is a clear start and an end point.
The user must go through a set of screens in a specific order.
The changes are not finalized until the last step.
Once complete it shouldn't be possible to repeat a transaction accidentally

Optimizing EF to populate a table using a DTO?

Upon attempting to populate a grid on the UI layer, the UI asks the BI layer for a list of results, EF returns the list of each result, and they are cast into a DTO that pulls in some additional information, this is converted to a list and returned to the UI layer.
The performance is impossibly slow. EF is creating a new context and hitting the DB for each individual result. This is because the DTO class will create a new dbcontext each time it is initialized if it is no longer open/active. Finalization of the class closes out the context. I believe this is what is killing performance.
Is there any way to batch something like this? In SQL i would performance a JOIN on the tables i need to get the resulting data loaded into a dataset. In EF when i create the DTO i then access the mapped objects relations and access data from other objects as such.
How should I access a large amount of records via EF to be returned to a UI layer grid when i need to access some information that is not stored in that particular entity object? (an example of this would be having a relation between users -> customers via the customer_userID -> userID PK. And wanting to display the User's Name, once i have the Customer object i need to then query the User object for the Users name in relation to that ID.
Anyone have any articles that can point me the correct way?
Functions that were passing a large amount of data to the UI layer were causing the issues. Often because the object from the DB layer had to have some operations performed on it before it could be passed to the UI layer. In essence some of the list generating functions were causing the store to create a new context for each individual request.
Just-in-time paging was one performance boost, so as to request a starting offset and a record count. What is important to note there is we had to create functions to simply return the total counts so the UI grids knew how many records they were dealing with.
The next fix was on the functions that apply BI rules to the objects before they are passed to the UI layer. In these cases we open a new context and pass that into the function, so it uses that context and only closes it out after the results are all completed.

Best approach to wait untill all service calls returned values in Flex PureMVC

I am writing an Adobe AIR application using PureMVC.
Imagine that I have an page-based application view ( using ViewStack ), and user is navigating through this pages in some way ( like clicking the button or whatever ).
Now for example I have an Account Infromation page which when instantiated or showed again needs to load the data from WebService ( for example email, account balance and username ), and when the data is returned I want to show it on my Account Information page in the proper labels.
The problem is when I will execute this three Web Calls, each of them will return different resultEvent at different time. I am wondering what is the best way to get the information that ALL of the service calls returned results, so I know that I can finally show all the results at once ( and maybe before this happens play some loading screen ).
I really don't know much about PureMVC, but the as3commons-async library is great for managing async calls and should work just fine in any framework-setup
http://as3commons.org/as3-commons-async/
In your case, you could create 3 classes implementing IOperation or IAsyncCommand (depending on if you plan to execute the operations immediately or deferred) encapsulating your RPCs.
After that is done you simply create a new CompositeCommand and add the operations to its queue.
When all is done, CompositeCommand will fire an OperationEvent.COMPLETE
BTW, the library even includes some pre-implemented common Flex Operations, such as HTTPRequest, when you download the as3commons-asyc-flex package as well.
I would do it in this way:
Create a proxy for each of three information entities (EMailProxy, BalanceProxy, UsernameProxy);
Create a delegate class which handles the interaction with your WebService (something like "public class WSConnector implements IResponder{...}"), which is used by the proxies to call the end ws-methods;
Create a proxy which coordinates all the three results (CoordProxy);
Choose a mediator which will coordinate all the three calls (for example it could be done by your ApplicationMediator);
Create notification constants for all proxy results (GET_EMAIL_RESULT, GET_BALANCE_RESULT, GET_USERNAME_RESULT, COORD_RESULT);
Let the ApplicationMediator get all 4 notifications;
it is important that you should not only wait for all three results but also be ready for some errors and their interpretation. That is why a simple counter could be too weak.
The overall workflow could look like this:
The user initiates the process;
Some mediator gets an event from your GUI-component and sends a notification like DO_TRIPLECALL;
The ApplicationMediator catches this notification, drops the state of the CoordProxy and calls all 3 methods from your proxies (getEMail, getBalance, getUsername).
The responses are coming asynchronously. Each proxy gets its response from the delegate, changes its own data object and sends an appropriate notification.
The ApplicationMediator catches those notifications and changes the state of the CoordProxy. When all three responses are there (may be not all are successful) the CoordProxy sends a notification with the overall result.
I know it is not the best approach to do such an interaction through mediators. The initial idea was to use commands for all "business logic" decisions. But it can be too boring to create the bureaucracy.
I hope it can help you. I would be glad to know your solution and discuss it here.

sort and search mvc list view without call to server

I have a simple ASPNET MVC list view which passes a custom built model object.First time through I need to go out to the server and return a list of objects and display on the view.
I am building the view to allow sorting by different columns, searching and paging, and I have written all the code for this. However every time I am going to the server and pulling the data.
Can I cut down on these DB roundtrips by using the list that I obtained first time ?
If so how do I pass it from the view back to the controller?
Viewdata, Tempdata - or pass the formcollection perhaps?
Take a look at http://www.knockoutjs.com this will give you a lot of functionality to manipulate the list in the browser and keeping the view in sync.
But it really depends on how big your list of objects is. If the quantity of data is large it is actually a more practical solution the way you implemented it already.
Actually, if you go back to your controller you'll be going to server.
I supose you really mean that you don't want to requery again your database to obtain data filtered, sorted and paginated and would like just to sort or paginate data from your model view classes with data alreay on the view.
Keep in mind that this type of operation doesn't have to be always better than requerying your database, as you'll be sending more info through the net back to the server and, usually, programatically sorting of list-like elements are operations less optimized than sorted retrievals from database.
The critical decision here will be between the cost of your database query and the size of your listview element. If your query is light and gets (or can get) many results, sorting it will be more expensive than requerying, while if your query is complex and usually throws few results then, effectively, it will be more efficient to sort data without requerying database.
Try to create a new controller method for the sort, this method will receive as a parameter your list view model class, and you'll need, somehow, to send back to your server that info. I usually use AJAX calls where I pass data as JSON to the controller.

Resources