Sunday, August 27, 2017

Delphi Event Bus and MVVM

In last ITDevCon, I held a speech on how to build modern applications with Delphi. In the speech I showed what are the good programming techniques and how to reach them in Delphi. The path was completed by presenting the MVVM pattern as solution. For more info about this pattern I suggest you these books:

  1. John Kouraklis, MVVM in Delphi
  2. Syromiatnikov, A., A Journey Through the Land of Model-View-* Design Patterns.

MVVM intents is to separate the domain logic from the presentation logic in three modules with distinct responsibilities:

  • handle the domain data (Model)
  • View state and business logic (View Model) 
  • Handle user interaction and rendering of the visual user interface (View)
The hardest part ( as in any software development ) is the Separation of Concerns (SOC), to keep separate layers so future changes do not interfere with each other. High cohesion and loose coupling, precisely! 
MVVM can manage UI Synchronization in two ways:
  1. Flow synchronization
    • uses direct calls between user interface components and domain. It is based on sequential command: read user input from text box A, processing it with method B, and write the result to text label C 
  2. Observer synchronization
    • the domain layer must implement a notification mechanism to which components of the user interface layer can subscribe. This allows the user interface components to update the state of the user interface when relevant changes in the domain occur
Both solutions keep the layers separated, but the Flow synchronization forces you to write an enormity of boiler plate code and write an Observer framework from zero ( why reinvent the wheel ? ) would be expensive in terms of developments.
Delphi Event Bus comes in our help! For those that doesn't know Delphi Event Bus (for short DEB), it is a publish/subscribe Event Bus framework for the Delphi platform.
DEB is designed to decouple different parts/layers of your application while still allowing them to communicate efficiently.
Simply put the Subscribe attribute on your subscriber method you are able to receive a specific event, and by specifying the TThreadMode in attribute you can choose the context where to deliver the event.
For example, if you have to interact with the UI EventBus can deliver events in the main thread or If your subscriber does long running tasks (HTTP request), EventBus can also use background threads to avoid UI blocking. Regardless where an event was posted the EventBus will manage Thread synchronization, so you can deliver an Event in the MainThread and the subscriber will receive it on a background thread and viceversa.
Look this demo (you need DMVC for server side part) to check how I resolve UI Synchronization in client/server context with REST request in background!









No comments :

Post a Comment