<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Oleg Varaksin on Medium]]></title>
        <description><![CDATA[Stories by Oleg Varaksin on Medium]]></description>
        <link>https://medium.com/@olegvaraksin?source=rss-140b4b117d7c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XDyY6OvGBY54ExghXIawLA.jpeg</url>
            <title>Stories by Oleg Varaksin on Medium</title>
            <link>https://medium.com/@olegvaraksin?source=rss-140b4b117d7c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:55:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olegvaraksin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Keyboard shortcuts with RxJS]]></title>
            <link>https://olegvaraksin.medium.com/keyboard-shortcuts-with-rxjs-ddcc2b939563?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddcc2b939563</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[keyboard-shortcuts]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 20:31:27 GMT</pubDate>
            <atom:updated>2025-01-12T20:31:27.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eGjvMUvAmHteyXIq" /><figcaption>Photo by <a href="https://unsplash.com/@nosoylasonia?utm_source=medium&amp;utm_medium=referral">Juan Gomez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this blog post, I’m sharing the TypeScript implementation of a manager class around keyboard shortcuts. It allows to register and deregister keyboard shortcuts for the whole application globally. The implementation was inspired by this great blog post: “<a href="https://notiz.dev/blog/simple-rxjs-keyboard-shortcuts">Create Keyboard Shortcuts with RxJS</a>”, but I improved the proposed implementation drastically by adding a bug fix and a couple of extensions. Just like in the original blog post, we’re leveraging RxJS. Let’s create a class called ShortcutManager. What is the purpose of this class? This class provides a single public method shortcut$ which is implemented as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04836a79112599aa447ddad08e15afd3/href">https://medium.com/media/04836a79112599aa447ddad08e15afd3/href</a></iframe><p>This shortcut function can be used to create Observable stream for any keyboard shortcut. A keyboard shortcut is a sequence of key codes, each representing a key of keyboard. Usage example as shortcut for Ctrl+F:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a97461c67ae3464fec17f5ebfd451136/href">https://medium.com/media/a97461c67ae3464fec17f5ebfd451136/href</a></iframe><p>The returned stream of keyboard events describes every pressed key. The undefined in the returned event stream means, all keys have been released. This is handy for some scenarios where you need to track the keyup events — and this is an extension of the originally proposed implementation in the mentioned blog post. Another examples from my current project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d58c9754f436840293b7ba373e5fd1b2/href">https://medium.com/media/d58c9754f436840293b7ba373e5fd1b2/href</a></iframe><p>Of course, we can construct any arbitrary sequence of shortcuts such as shortcut$(ShortcutKey.Alt, ShortcutKey.F1, ShortcutKey.Digit0)for the three pressed keys “Alt+F1+0”. Most of the time, the order of pressed keys is important, so that the implementation considers the order. In the last example, first the “Alt” key should be pressed, then the “F1” and the “0” digit at the end.</p><p>Let’s speak about ShortcutKey and explore every private method in the ShortcutManager in details. The class ShortcutKey represents a single shortcut key. I’m gonna to show an excerpt only. For more details regarding defined constants see the official documentation “<a href="https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_code_values">Code values for keyboard events</a>” and the property “code” there.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/174a340a3a92a61a1a93d937cc321d89/href">https://medium.com/media/174a340a3a92a61a1a93d937cc321d89/href</a></iframe><p>Please see the comments — for the sake of convenience, we don’t need to list different physical keys like “AltLeft” and “AltRight” for a single logical key. We can use a logical key “Alt” and shorten the syntax for key registration. This is a handy extension in comparison to the original blog post. To achieve this goal I added a method which generates <a href="https://en.wikipedia.org/wiki/Cartesian_product">cartesian product</a> (see the method invocation in the public shortcut$).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c2aa1e17f05295356111aa61309600/href">https://medium.com/media/12c2aa1e17f05295356111aa61309600/href</a></iframe><p>Another two private methods are listed below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8292290db9767a9e329e2374cadb7b2c/href">https://medium.com/media/8292290db9767a9e329e2374cadb7b2c/href</a></iframe><p>As you see, we buffer pressed keys to be able to check later if all of them are released. This is a bug fix I mentioned above. The combineLatest RxJS operator waits for all input (= pressed keys) and emit all the latest values of all inputs. The registration of keydown and keyup keyboard events occurs on the document object by means of the fromEvent RxJS operator.</p><p>The last remaining private method checkPressedKey (used within the filter) is a check for the exactly count of the pressed keys. As you see, as soon as all keys get released, the subscribers of theshortcut$ will be informed. It also check the key sequence, i.e. order of the pressed keys. It is a requirement here, but was an optional add-on in the <a href="https://notiz.dev/blog/simple-rxjs-keyboard-shortcuts">original implementation</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d26b980879792fb9002c951229c0a22/href">https://medium.com/media/9d26b980879792fb9002c951229c0a22/href</a></iframe><p>That’s all. Give it a try!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddcc2b939563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Loosely coupled communication between services in TypeScript based projects]]></title>
            <link>https://olegvaraksin.medium.com/loosely-coupled-communication-between-services-in-typescript-based-projects-9e7729e72d2e?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e7729e72d2e</guid>
            <category><![CDATA[mediator-pattern]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[communication]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Sat, 09 Dec 2023 21:06:24 GMT</pubDate>
            <atom:updated>2023-12-09T21:06:24.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ROWzFThbzQfp02eK" /><figcaption>Photo by <a href="https://unsplash.com/@ptrikutam?utm_source=medium&amp;utm_medium=referral">Pavan Trikutam</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently in one of my Angular / TypeScript projects, I wanted to implement an event based communication between several service classes, called handlers in my project. There are a lot of handlers which need to interchange data. I didn’t want to inject them into each other — it is a bad design which leads to a not well-arranged application and circular dependencies. Handlers should not know each other. The handler classes in my project are registered as multi providers under an InjectionToken named as ELEMENT_HANDLER. Short excerpt:</p><pre>@Component({<br>  ...<br>  providers: [<br>    {<br>      provide: ELEMENT_HANDLER,<br>      useClass: EdgeHandler,<br>      multi: true<br>    },<br>    {<br>      provide: ELEMENT_HANDLER,<br>      useClass: MainSignalHandler,<br>      multi: true<br>    },<br>    {<br>      provide: ELEMENT_HANDLER,<br>      useClass: PerronHandler,<br>      multi: true<br>    },<br>    ...<br>]</pre><p>I thought, a kind of event bus and a loosely coupled communication like in Sping framework, would be great.</p><blockquote>In Spring, you can publish an event with payload and all methods annotated with @EventListener and having the same event type in the method signature can receive it. You can read e.g. in <a href="https://reflectoring.io/spring-boot-application-events-explained/">this article</a> how it works.</blockquote><p>How to facilitate a similar approach in TypeScript? In TypeScript, we can write custom <a href="https://www.typescriptlang.org/docs/handbook/decorators.html">Decorators</a>! What we will need, is a smart parameter decorator which will notice a class, a method and a type of event class from the place where it appears. Such mapping information should be registered in a singleton object to be able to access it anywhere. A parameter decorator is declared before a parameter declaration. The communication pattern we would like to use, is demonstrated in the following code snippet.</p><pre>// 1. handler<br>await SspElementMediator.getInstance().publish(<br>  new TrainPositionSelectedEvent(trainNumber)<br>);<br><br>// 2. handler<br>async onTrainPositionSelected(<br>  @SspElementEvent event: TrainPositionSelectedEvent): Promise&lt;void&gt; {<br>  // do something with event<br>}</pre><p>Another example where the event listener returns a value to the caller looks like as follows (yes, it’s not only “fire-and-forget” communication):</p><pre>// 1. handler<br>const selected = await SspElementMediator.getInstance()<br>  .requestAndTakeFirstValue&lt;boolean&gt;(<br>    new IsTrainPositionSelectedEvent(trainRun.trainNumber)<br>);<br><br>// 2. handler<br>async onIsTrainPositionSelected(<br>  @SspElementEvent event: IsTrainPositionSelectedEvent): Promise&lt;boolean&gt; {<br>  // do something with event<br>  return true / false;<br>}</pre><p>As you could see, we want to implement the decorator @SspElementEvent. For the methods which act as event listeners, the return type Promise is expected. In your projects, you can define any other types. An example of the event classes:</p><pre>export class TrainPositionSelectedEvent extends AbstractSspEvent {<br>  constructor(public trainNumber: string | undefined) {<br>    super();<br>  }<br>}<br><br>export class IsTrainPositionSelectedEvent extends AbstractSspEvent {<br>  constructor(public trainNumber: string) {<br>    super();<br>  }<br>}</pre><p>To achieve our intention, we need Metadate Reflection API to determine information on used types at runtime. Angular projects already have this dependency because Angular uses decorators intensively. That means, we don’t need to install <a href="https://www.npmjs.com/package/reflect-metadata">reflect-metadata</a>. We only need to import “reflect-metadata”, e.g. in the file where we are going to write a parameter decorator.</p><pre>import &quot;reflect-metadat&quot;;</pre><p>Ensure that you also have these two options in your tsconfig.json file:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;experimentalDecorators&quot;: true,<br>    &quot;emitDecoratorMetadata&quot;: true<br>  }<br>}</pre><p>With these preparations, additional design-time type information will be exposed at runtime. The type information can be accessed via Reflect.getMetadata for design:type, design:paramtypes, and design:returntype.</p><blockquote>Decorators are just plain functions or so-called decorator factories, if we need to pass in some values from outside — read the official <a href="https://www.typescriptlang.org/docs/handbook/decorators.html">TypeScript documentation</a>.</blockquote><p>Let’s write our parameter decorator.</p><pre>/**<br> * TypeScript decorator to annotate a method parameter in SSP element<br> * handler if the method should act as event listener. The event listener<br> * method should return a Promise, otherwise the event binding will not<br> * be registered.<br> */<br>export function SspElementEvent(target: object, methodName: string) {<br>  // use reflection to determine the type of method parameter<br>  const paramTypes: any[] = Reflect<br>    .getMetadata(&quot;design:paramtypes&quot;, target, methodName);<br>  if (paramTypes.length != 1) {<br>    console.warn(`Event listener ${target.constructor.name}#${methodName} \<br>                  may only have one method parameter`);<br>    return;<br>  }<br><br>  // validate return type<br>  const returnType = Reflect<br>    .getMetadata(&quot;design:returntype&quot;, target, methodName);<br>  if (!isPromiseLike(returnType)) {<br>    console.warn(`Event listener ${target.constructor.name}#${methodName} \<br>                  may only have Promise like return types`);<br>    return;<br>  }<br><br>  const eventName = paramTypes[0].name;<br>  SspElementMediator.getInstance()<br>    .putEventBinding(eventName, target.constructor.name, methodName);<br>}<br><br>/**<br> * This approach is called duck typing. We basically say:<br> * &quot;if the value is an object and has these specific properties/methods,<br> * then it must be a promise&quot;.<br> */<br>const isPromiseLike = (p: any) =&gt; p &amp;&amp;<br>  (typeof p === &#39;object&#39; || typeof p === &#39;function&#39;) &amp;&amp;<br>  typeof p.resolve === &#39;function&#39; &amp;&amp; typeof p.reject === &#39;function&#39;;</pre><p>What we do this — we create a mapping (or event binding) between class + method and the event type. This is accomplished by invoking putEventBinding on the SspElementMediator. The mediator is a behavioral design pattern that lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects and forces them to collaborate only via a mediator object.</p><p>The decorator function is executed quite early — before all Angular’s initialization jobs. So, at this time we can not access the handlers with the InjectionToken, and can not set them into the SspElementMediator. We can do it inprovide within useFactory.</p><pre>{<br>  provide: SspElementMediator,<br>  useFactory: (elementHandlers: SspElementHandler&lt;any&gt;[]) =&gt;<br>    SspElementMediator.getInstance().withElementHandlers(elementHandlers),<br>  deps: [ELEMENT_HANDLER]<br>}</pre><p>Now, we can inject SspElementMediatorin any component, service, etc. where we want. Let’s look at the central class SspElementMediator. The method putEventBinding called from the decorator function is pretty simple.</p><pre>export class SspElementMediator {<br><br>  private static _instance: SspElementMediator;<br><br>  private readonly _eventBindings:<br>    Map&lt;string, ClassMethodBinding[]&gt; = new Map();<br>  private _elementHandlers?: SspElementHandler&lt;any&gt;[];<br><br>  private constructor() {<br>  }<br><br>  /**<br>   * Returns a singleton instance.<br>   */<br>  static getInstance(): SspElementMediator {<br>    if (!SspElementMediator._instance) {<br>      SspElementMediator._instance = new SspElementMediator();<br>    }<br>    return SspElementMediator._instance;<br>  }<br><br>  /**<br>   * Creates an event binding, i.e. associates given event&#39;s class name<br>   * with the given class method.<br>   */<br>  putEventBinding(eventName: string,<br>                  className: string,<br>                  methodName: string) {<br>    let classMethodBindings = this._eventBindings.get(eventName);<br>    if (classMethodBindings === undefined) {<br>      classMethodBindings = [];<br>    }<br>    classMethodBindings.push({className, methodName});<br>    this._eventBindings.set(eventName, classMethodBindings);<br>  }<br>}</pre><p>There three methods in SspElementMediator which are placed at disposal for callers:</p><pre>/**<br> * Publishes given event to all SSP element handlers which are able<br> * to handle it according to the event binding. It works as<br> * &quot;fire-and-forget&quot; for emitters which are not interested<br> * in return values.<br> */<br>async publish(event: AbstractSspEvent): Promise&lt;void&gt; {<br>  const classMethodBindings = this._eventBindings<br>    .get(event.constructor.name) ?? [];<br>  for (const classMethodBinding of classMethodBindings) {<br>    const elementHandler = this.findElementHandler(<br>      classMethodBinding.className) as any;<br>    if (elementHandler !== undefined) {<br>      await (elementHandler[classMethodBinding.methodName](event)<br>        as Promise&lt;any&gt;).catch(err =&gt; console.error(<br>          `Error while invoking ${classMethodBinding.className}# \<br>           ${classMethodBinding.methodName} with event \<br>           ${JSON.stringify(event)}: ${err}`));<br>    }<br>  }<br>}</pre><pre>/**<br> * Sends given event to all SSP element handlers which are able to handle<br> * it according to the event binding and returns the first promise with<br> * a return value. The return value can be undefined if the called event<br> * listener method throws an exception or the event listener for the<br> * given event was not found. Most of the time we want a peer-to-peer<br> * communication between handlers, so that this is a useful method<br> * in such case.<br> */<br>async requestAndTakeFirstValue&lt;T&gt;(event: AbstractSspEvent):<br>  Promise&lt;T | undefined&gt; {<br>  const classMethodBindings = this._eventBindings<br>    .get(event.constructor.name) ?? [];<br>  if (classMethodBindings.length &gt; 0) {<br>    const {className, methodName} = classMethodBindings[0];<br>    const elementHandler = this.findElementHandler(className) as any;<br>    if (elementHandler !== undefined) {<br>      try {<br>        return elementHandler[methodName](event);<br>      } catch (err) {<br>        console.error(`Error while invoking ${className}#${methodName} \<br>          with event ${JSON.stringify(event)}: ${err}`);<br>        return undefined;<br>      }<br>    }<br>  }<br>  return undefined;<br>}</pre><pre>/**<br> * Sends given event to all SSP element handlers which are able to handle<br> * it according to the event binding and returns a promise with array<br> * of EventListenerResult objects. Every EventListenerResult describes<br> * a return result from the appropriate event listener the given event<br> * was handled by.<br> */<br>async request&lt;T&gt;(event: AbstractSspEvent):<br>  Promise&lt;EventListenerResult&lt;T | undefined&gt;[]&gt; {<br>  ...<br>}</pre><blockquote>As you noticed, we get the name of the event class by calling even.constructor.name. The same technique was also used in the decorator — there we got the class name by calling target.constructor.name.</blockquote><p>Last but not least, the method findElementHandler called within the three methods above.</p><pre>private findElementHandler(className: string):<br>  SspElementHandler&lt;any&gt; | undefined {<br>  for (const elementHandler of this.getElementHandlers()) {<br>    if (className === elementHandler.constructor.name) {<br>      return elementHandler;<br>    }<br>  }<br>  return undefined;<br>}</pre><p>For the sake of convenience, I skipped some complicated details. Try to write them by yourself as exercise :-). Any suggestions, feedback and comments are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e7729e72d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert world to screen coordinates and vice versa in WebGL]]></title>
            <link>https://olegvaraksin.medium.com/convert-world-to-screen-coordinates-and-vice-versa-in-webgl-c1d3f2868086?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1d3f2868086</guid>
            <category><![CDATA[webgl]]></category>
            <category><![CDATA[coordinate-systems]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webgl2]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 21:03:20 GMT</pubDate>
            <atom:updated>2023-04-24T21:03:20.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ZFGd1jnA4WwrRdiRk5KMBQ.png" /><figcaption>Credits to <a href="https://learnopengl.com/">https://learnopengl.com/</a></figcaption></figure><p>In this blog post, we will discuss different coordinate systems in <a href="https://www.khronos.org/api/webgl">WebGL</a> and implement two functions in TypeScript. The first function will convert the world coordinates to screen coordinates (aka canvas coordinates) and the second one will do the opposite — convert screen coordinates to world coordinates. This is a quite common task. Normally, we construct a <strong>scene</strong> with different objects in world coordinates. Such coordinates can be e.g. time, meter, temperature or everything what you want. In WebGL, everything gets rendered into a canvas. Often you need to know for a given point in world coordinates what is the position of that point in 2D — on the screen (canvas) in pixel coordinates. The opposite is also true. E.g. you interact with mouse on a visual canvas and would like to know the object’s world coordinate below the mouse cursor. In this blog post, we will only implement the mentioned conversion formulas in the 2D space.</p><p>If you look at the picture above, you will see that everything starts with <strong>local coordinates</strong>. When you’re creating a model of 2D / 3D objects, you create them at the origin (0,0,0). The model can be easily built at this point. Local coordinates are the coordinates of your object relative to its local origin.</p><p>In the real life, different 2D / 3D objects are placed somewhere in the world space at different coordinates. The coordinates of your objects are transformed from local to <strong>world coordinates</strong>. This happens with the help of translation, scaling and rotation. Well, there is skewing too, but it’s a rare transformation.<strong> </strong>Every transformation can be represented as a matrix. There are a lot of resources about transformation matrices. E.g. a simple<a href="https://www.tutorialspoint.com/computer_graphics/2d_transformation.htm"> introduction to 2D transformations</a>. Such transformations for an object can be multiplied and build a final transformation which is called the model matrix. As already said, all particular objects are normally grouped hierarchically within a scene (often called a scene graph too). You can read a nice explanation for such structure on <a href="https://webglfundamentals.org/webgl/lessons/webgl-scene-graph.html">WebGLFundamentals</a>. Of course, the scene as a whole can be translated, scaled and rotated as well. Every transformation on the scene gets recursively applied to all objects in this scene. Just two examples from one of my projects at <a href="https://company.sbb.ch/">Swiss Federal Railways (SBB)</a> how the scenes in world coordinates can look like (just two cropped scenes’ parts).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*MwHqcBeSqphx-G1sUeDW4A.png" /></figure><p>X-coordinate in this scene is defined as numeric index 0, … N. There is a grey vertical line per index labeled in green. Y-coordinate is defined in time intervals. The objects in the scene are train routes. The second scene is defined in pixel (the same unit as screen coordinates), but the origin and axes of the scene (red color) are different from the origin and axes of the HMTL canvas (blue color). The objects in the scene are railway elements on the track network such as edges, signals, track numbers, points, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*rocDwxaCLhl20RSs_gJiKQ.png" /></figure><p>The next stage is a view space. The view space is the result of transforming the world-space coordinates to <strong>view coordinates</strong> that are in front of the user’s view. The view space is the space as seen from the camera’s point of view. Such transformation means that the camera is moving around the world. Well, in fact, the world is moving, and the camera is still. A matrix describing such transformation considers amongst others a camera’s position and view direction. Per default, the camera is positioned at the point (0,0,0) where the camera is looking down the z-axis. In this blog post, we will take a default position. That means, the view matrix is an identity matrix and can be skipped entirely.</p><p>In a WebGL program, data is typically uploaded to the GPU with its own coordinate system. The coordinates in such coordinate system are restricted to (1,1,1) and (-1,-1,-1). The x, y and z coordinates of each vertex should be between -1.0 and 1.0. Coordinates outside this range will not be visible. Such coordinates are normally called <strong>clip coordinates</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*1cSGq72ccZ5uqoh1I1xWCw.png" /></figure><p>They are often called normalized device coordinates (NDC) too. Such coordinate system is used in vertex shader. Vertex shader is a stage in the rendering pipeline that handles the processing of individual vertices which are given then to the rasterizer (rasterizer transforms vertices to pixels on screen). Projection to clip coordinates is accomplished by using a projection matrix. There are two main projections: orthographic projection and perspective projection. An orthographic projection matrix defines a cube-like frustum box where each vertex outside this box is clipped. CAD programs normally operate with such projection. Perspective projection is normally used in games where a real life is simulated and the objects that are farther away appear much smaller. I have found one picture on Stack Overflow which demonstrates both projections at a glance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*1ByGRgA8dxWV4X17iLGQRQ.png" /></figure><p>In the last step, the clip coordinates should be transformed to <strong>screen coordinates</strong>. This process transforms the coordinates from -1.0 and 1.0 to the coordinate range defined by the visible canvas. The canvas has its own coordinate system. The upper left corner of the screen coordinate system is (0,0) and the lower right is (width,height).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*jA2kQcfKQn0MUDB8GMf5aA.png" /></figure><p>The transformation occurs by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/viewport">viewport method on the WebGLRenderingContext</a>. That’s all to five different coordinate systems that are important for us. Let’s start with mathematics. Look at the first picture to this blog post please. We will define a point in the clip space as a vector C. The x coordinate is defined as Cx and the y coordinate as Cy respectively. We can convert a local coordinate to a clip coordinate with the help of <strong>model-view-projection</strong> matrix. We can also convert a world coordinate to a clip coordinate with the help of view-projection matrix or more general with the help of model-view-projection matrix because the scene itself can be transformed too (translated, scaled or rotated). We will define a point in the world space as a vector W. The x coordinate is defined as Wx and the y coordinate as Wy respectively. Furthermore, we will designate the model-view-projection matrix as P. With these designations in mind, we come to the formulas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*pnl7ZJiAlhr8pfIbp5mzvA.png" /></figure><p>In the last formula, we introduced the screen coordinates as a vector S and expressed the clip coordinates by the screen coordinates according to the explained coordinate systems above. For vector and matrix math, we will use the well-known library <a href="https://github.com/toji/gl-matrix">gl-matrix</a>. The conversion function which converts a screen point to a world point can be implemented as follows:</p><pre>function convertScreenToWorldPoint(xScreen: number, yScreen: number,<br>                                 canvasWidth: number, canvasHeight: number,<br>                                 projection: mat3): [number, number] {<br>  const clipCoord: vec2 = vec2.fromValues(<br>    2.0 * xScreen / canvasWidth - 1.0,<br>    1.0 - 2.0 * yScreen / canvasHeight);<br><br>  const worldVec = vec2.transformMat3(<br>    vec2.create(),<br>    clipCoord,<br>    mat3.invert(mat3.create(), projection));<br><br>  return [worldVec[0], worldVec[1]];<br>}</pre><p>As you see, it’s simple enough. The last formula can be paraphrased and written down in another way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Y-qxDglwsOtuRg7XzZxqBw.png" /></figure><p>Now, let’s express the screen coordinates on the left side by the clip coordinates:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*BJSql2yriDXOqSXf53PoFA.png" /></figure><p>That gives us a conversion from a world point to a screen point resulting in this implementation:</p><pre>function convertWorldToScreenPoint(xWorld: number, yWorld: number,<br>                                 canvasWidth: number, canvasHeight: number,<br>                                 projection: mat3): [number, number] {<br>  const clipCoord: vec2 = vec2.transformMat3(<br>    vec2.create(),<br>    vec2.fromValues(xWorld, yWorld),<br>    projection);<br><br>  const screenVec = vec2.fromValues(<br>    (1.0 + clipCoord[0]) * canvasWidth / 2.0,<br>    (1.0 - clipCoord[1]) * canvasHeight / 2.0);<br><br>  return [Math.round(screenVec[0]), Math.round(screenVec[1])];<br>}</pre><p>As already said, in the reality, you should take all scene transformations into account. That means, the projection matrix passed to the functions is a combined matrix out of model-view-projection transformations. A simple 2D projection matrix with the given bounds and without any model-view transformations can be generated as follows (just to give an example):</p><pre>function getProjection(canvasWidth: number, canvasHeight: number): mat3 {<br>  return mat3.projection(mat3.create(), canvasWidth, canvasHeight);<br>}</pre><p>That’s all. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d3f2868086" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison of language features between Java, Kotlin, Dart and TypeScript]]></title>
            <link>https://olegvaraksin.medium.com/comparison-of-language-features-between-java-kotlin-dart-and-typescript-93a2c056a3e7?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/93a2c056a3e7</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming-languages]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 13:00:57 GMT</pubDate>
            <atom:updated>2022-01-03T13:00:57.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5DmiHGGK5g3oXb6d" /><figcaption>Photo by <a href="https://unsplash.com/@max_duz?utm_source=medium&amp;utm_medium=referral">Max Duzij</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some time ago I blogged about language features in TypeScript and Dart which I miss in Java.</p><p><a href="https://olegvaraksin.medium.com/14-language-features-in-typescript-and-dart-you-may-miss-in-java-6bdc11c6fee7">14 language features in TypeScript and Dart you may miss in Java</a></p><p>In this blog post, due to my new expertise in Kotlin, I would like to consider Kotlin too. Every programming language has a main focus where it is used. Java is primarily used in backend, Kotlin in backend + frontend (Android) and Dart, TypeScript are mostly used in frontend.</p><p>I have created a comparison of various language features in form of compact tabular cheat sheet. I only considered features which are (partially) existing <strong>at least in two</strong> programming languages. There is much similarity across different programming languages. But sure, there are unique features per programming language too. Such features are not considered due to huge amount of them. Furthermore, I have taken the latests and greates versions into account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Qk4fAbeSDuLIrMKaI1HtHA.png" /></figure><p><em>List of references:</em></p><ul><li><a href="https://docs.oracle.com/en/java/javase/17">Java Docs</a></li><li><a href="https://kotlinlang.org/docs">Kotlin Docs</a></li><li><a href="https://dart.dev/guide">Dart Docs</a></li><li><a href="https://www.typescriptlang.org/docs/handbook/intro.html">TypeScript Docs</a></li></ul><p>Do you know more features to be compared? Feel free to leave comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93a2c056a3e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clever cache for Reactor’s Mono objects]]></title>
            <link>https://olegvaraksin.medium.com/clever-cache-for-reactors-mono-objects-d18a5451414b?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d18a5451414b</guid>
            <category><![CDATA[mono]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[reactive-streams]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Tue, 27 Jul 2021 21:09:23 GMT</pubDate>
            <atom:updated>2021-07-27T21:09:23.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWwDyYf1PZwTfJl9" /><figcaption>Photo by <a href="https://unsplash.com/@ohhbee?utm_source=medium&amp;utm_medium=referral">Olivia Bauso</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data caching is a widespread technique in the programming. It allows to quickly retrieve data without making long-running operations. But there is a problem with caching of data retrieved as result of some long-running operation. If a cache value is missed, it will be requested. If it is requested by a long-running HTTP request or SQL command, the next request for the cache value can leads to multiple HTTP requests / SQL commands again and again. I was looking for a cache implementation which solves this issue in projects using <a href="https://projectreactor.io/">Project Reactor</a>. Project Reactor is built on top of the Reactive Streams Specification — a standard for building reactive applications. You probably know Mono and Flux objects from <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html">Spring WebFlux</a>. Project Reactor is the reactive library of choice for Spring WebFlux.</p><p>In this article, I will suggest a reactive cache implementation inspired by CacheMono from Reactor’s addons project. We will assume, that the result of a long-running HTTP request or SQL command is represented as aMono object. A Mono object is “materialized” and cached in form of Reactor’s <a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Signal.html">Signal</a> object which represents a Mono. Signals are “dematerialized” to Mono’s if a cache value is requested by the lookup method. Multiple lookups with the same key will retieve the same Mono object, so that a long-running operation is only triggered once!</p><p>Let’s create a class CacheMono with three factory methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e09a077811dc8e6b552e26a994ffc29f/href">https://medium.com/media/e09a077811dc8e6b552e26a994ffc29f/href</a></iframe><p>Not yet cached values will be retrieved either by valueSupplier or valuePublisher. The first one uses the “pull” principle and the second one uses the “push” principle to retrieve not yet cached values. That means, either valueSupplier or valuePublisher along with keyExtractor and valueExtractor should be set.</p><p>Keep in mind: if you create more than one CacheMono from the same value publisher, you should pass in a Flux stream which caches the history and emits cached items from the beginning to future subscribers. This is necessary because this CacheMono implementation subscribes to the passed in Flux stream in order to fill cache automatically once the source Flux stream publishes values (reactive “push” way vs. “pull” provided by another factory method). The simplest way to create a such Flux stream from existing one would be invoking of cache() method on any Flux stream.</p><p>As you could see, we cache instances of CacheMonoValue. This is just a wrapper around Mono or Signal. We can implement this class as an inner class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcaabda8ed20daea5f20a6c57de2e104/href">https://medium.com/media/bcaabda8ed20daea5f20a6c57de2e104/href</a></iframe><p>We will see in few words, that a Mono value from a long-running operation is cached immediately. The same Mono instance is retrieved for all subsequent lookups with the same key. Once the result of Mono is available, the real value is cached as Signal under the same key. Well, step by step. Look at the lookup method first. It uses a well-known pattern: if value is missed in the cache, the logic within the switchIfEmpty operator gets executed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f5e8ad2f541d19f9ac40dc7b29c654b/href">https://medium.com/media/1f5e8ad2f541d19f9ac40dc7b29c654b/href</a></iframe><p>In the onCacheMissResume, a missed value will be retieved by the mentioned above valueSupplier or valuePublisher. As I said, the value is cached immediately as a Mono object and is returned for all subsequent lookups. As soon as the value from the long-running operation is available, the logic within monoValue.doOnEach(...) is executed. The value is encapsulated in Signal and can be returned by invokingsignal.get().</p><p>Let’s implement some convenient methods as well. Especially methods which return already existing (cached) values from the cache.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c7e0cdf9c252a1fb6c0cd33fb4a8de7/href">https://medium.com/media/9c7e0cdf9c252a1fb6c0cd33fb4a8de7/href</a></iframe><p>The usage of CacheMono class is simple. Just two code snippets from my current project. The first one creates a CacheMono instance by calling CacheMono.fromSupplier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/deb458defcd16bb970937bd4a86f9548/href">https://medium.com/media/deb458defcd16bb970937bd4a86f9548/href</a></iframe><p>The second one creates a CacheMono instance by calling CacheMono.fromPublisher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c981e386618d5f89fdfb167c979dc65/href">https://medium.com/media/4c981e386618d5f89fdfb167c979dc65/href</a></iframe><p>That’s all. Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d18a5451414b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performing long-running tasks in non-blocking manner with Java’s CompletableFuture and Reactor’s…]]></title>
            <link>https://olegvaraksin.medium.com/performing-long-running-tasks-in-non-blocking-manner-with-javas-completablefuture-and-reactor-s-e647cbd8885b?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e647cbd8885b</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[reactive-streams]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Tue, 25 May 2021 10:58:18 GMT</pubDate>
            <atom:updated>2021-05-25T11:15:29.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performing long-running tasks in non-blocking manner with Java’s CompletableFuture and Reactor’s Mono and Flux</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5rsk2zvbsMJjvs1F" /><figcaption>Photo by <a href="https://unsplash.com/@chrisds311?utm_source=medium&amp;utm_medium=referral">Christian De Stradis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Java, long-running tasks can be run in non-blocking manner by means of <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/CompletableFuture.html">CompletableFuture</a>. CompletableFuture is used for asynchronous programming in Java. Normally, we can asynchronously run a task by the method supplyAsync(Supplier&lt;U&gt; task) which returns a new CompletableFuture. The task is running in a thread pool and the returned CompletableFuture is completed when the task is done. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fc7d6eef7b056eacf1eb22f04deca42/href">https://medium.com/media/8fc7d6eef7b056eacf1eb22f04deca42/href</a></iframe><p>The method get() waits if necessary for the future to complete, and then returns the computation result. Useful methods on CompletableFuture are</p><ul><li><strong>thenAccept(Consumer&lt;? super T&gt; action)</strong><br>It can run some code after receiving some value from asynchronously running task without returning any value.</li><li><strong>thenApply(Consumer&lt;? super T&gt; action)</strong><br>It can run some code after receiving some value from asynchronously running task and return another value after that.</li><li><strong>thenRun(Runnable action)</strong><br>It can run some code after normal completion without returning any value.</li></ul><p>There are also three other variants of these methods: thenAcceptAsync, thenApplyAsync, thenRunAsync. They let run some code in another execution thread, different from the thread defined by the CompletableFuture. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f199ab1786bbd4a3cd4879906b1c9ea1/href">https://medium.com/media/f199ab1786bbd4a3cd4879906b1c9ea1/href</a></iframe><p>ACompletableFuture can also be explicitly completed using complete(T value) or completeAsync(Supplier&lt;? extends T&gt; supplier). T is the type of value returned by get(). We can create a method which creates CompletableFuture and returns it immediately. Another threads or asynchron methods are responsible for executing some computations and completing the CompletableFuture with an appropriate result.</p><p>Let’s write a LongRunningTaskService expecting a task in form of Java’s Supplier and returning a CompletableFuture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e88910951c1aa8b7bfe53610fbf775/href">https://medium.com/media/62e88910951c1aa8b7bfe53610fbf775/href</a></iframe><p>We will see a usage further, no worries. For now, let’s discuss the <a href="https://projectreactor.io/">Project Reactor</a> with the <a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html">Sping WebFlux</a>. Project Reactor is a reactive library for building non-blocking applications which is based on the Reactive Streams Specification — a concept, adopted by various implementations such as RxJava, Java‘ Flow classes, Akka Streams. At first glance, Reactive Streams and Java 8 Streams look pretty similar. But there is an important difference: Reactive Streams are <strong>push-based</strong> and Java 8 Streams are <strong>pull based</strong>. In Java 8 Streams you normally iterate over collections, pull values, apply operators like filter, map, flatMap, etc., and terminate the processing by collecting or grouping result values. Reactive Streams have similar operators, but they offer <strong>Publishers </strong>that notify <strong>Subscribers </strong>of newly available values as they come. In the Project Reactor, there are two heavily used publishers:</p><ul><li>Mono&lt;T&gt;. It returns 0 or 1 element of type T.</li><li>Flux&lt;T&gt;. It returns 0…N elements of type T. The count of published elements can be potentially infinite.</li></ul><p>Just a simple example how to create and combine two Flux streams with a zip operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3dbb8e4c4ca30d893d6c485e8920af8e/href">https://medium.com/media/3dbb8e4c4ca30d893d6c485e8920af8e/href</a></iframe><p>Spring WebFlux is a non-blocking framework built on Project Reactor that makes it possible to build reactive applications on top of HTTP layer. It does not require the Servlet API. Per default, Spring WebFlux uses an embedded HTTP/2 enabled server <strong>Reactor Netty</strong>. The major difference to Spring MVC — the REST controller’s methods return the reactive types Mono and Flux. An example from my current project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3331118002356998ed32f1e5b0d8f51a/href">https://medium.com/media/3331118002356998ed32f1e5b0d8f51a/href</a></iframe><blockquote>A client that initiates a request, doesn’t get blocked with Mono and Flux. The corresponding request thread goes back into the thread pool. Once the result of the long-running operation is available, it will be pushed to the client.</blockquote><p>But back to our service class LongRunningTaskService. Let’s extend it with two additional methods returning Mono and Flux respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0184d37374fa4705eee9378e3764af3/href">https://medium.com/media/f0184d37374fa4705eee9378e3764af3/href</a></iframe><p>What is the sink in the consumer function (sink) -&gt; {...}? This is an emitter of type FluxSink which is used for emitting values to subscribers of Flux stream created by the Flux.create(). A full documentation of the create() method can be found <a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html#create-java.util.function.Consumer-">here</a>. The next code snippet demonstrates the usage of all three methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be96d9ce1867daa6f688188a16369ffe/href">https://medium.com/media/be96d9ce1867daa6f688188a16369ffe/href</a></iframe><p>Output:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e41b269a8ec68fd48070c60d07bd406/href">https://medium.com/media/8e41b269a8ec68fd48070c60d07bd406/href</a></iframe><p>Project Reactor solve many programming problems in an elegant way. For instance, you can implement the “retry pattern with exponential back-off” (design pattern for resilience). In the next blog post, I will suggest a reactive solution how to load remote data in parallel from paginated REST API (lazy data pagination). Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e647cbd8885b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple implementation of Request-Reply pattern over messaging in Dart]]></title>
            <link>https://olegvaraksin.medium.com/simple-implementation-of-request-reply-pattern-over-messaging-in-dart-d727e33e4711?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d727e33e4711</guid>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[request-response]]></category>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Fri, 14 May 2021 19:09:21 GMT</pubDate>
            <atom:updated>2021-05-15T07:53:32.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SfKtklP6f_lsSJYs" /><figcaption>Photo by <a href="https://unsplash.com/@cass_?utm_source=medium&amp;utm_medium=referral">Cassandra Dray</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The request-reply pattern over messaging uses a message broker as a communication medium. There are a lot of advantages of this pattern over traditional RESTful communication between client and server. Just to mention a few:</p><ul><li>Communication over messaging increases the system availability. Many message broker offer <em>message delivery guarantees</em>.</li><li>A message broker can buffer last messages which are then available for upcommig subscribers. This feature makes possible for an application to retrieve the last system state on <em>initial load</em>.</li><li>Using an unique identifier, called <em>correlation Id</em>, you can also solve the problem when some requests are processed faster than the others. Belonging together response and request should have identical <em>correlation Id</em>.</li></ul><p>The following picture is taken from the <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/RequestReply.html">Enterprise Integration Patterns</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*MZjd2YAeC-yM7nYR.gif" /></figure><p>This is a quite normally <em>publish–subscribe</em><strong> </strong>messaging system. The publishers and subscribers are unaware of each other. Messages in publish-subscribe system are routed by a centralised broker.</p><p>Currently, I’m developing a mobile app in <a href="https://flutter.dev/">Flutter</a> and <a href="https://dart.dev/">Dart</a>. Due to entire message based communication with backend, we have picked the package <a href="https://pub.dev/packages/mqtt_client">mqtt_client</a> — MQTT client for Dart. Then we implemented a service class MessagingService which can listen to incoming data from the specified topics and send some data over the topics by means of Dart’s <em>mqtt_client</em>. These are two typically tasks in a publish–subscribe<strong> </strong>messaging system. Below is a code snippet from MessagingService with appropriate methods for each task (full implementation is not necessary to understand this blog post).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9de65d49dbeed06921dac34d1df85b8/href">https://medium.com/media/e9de65d49dbeed06921dac34d1df85b8/href</a></iframe><p>One challenge was how to publish and receive asynchronous messages in a synchronous manner. What we wanted was this call sequence: subscribe to a defined topic for incoming data → send a message to another topic → wait until a response message is arrived on the subscribed topic → evaluate the response and continue with program flow. To accomplish this challenge, we are going to implement aRequestReplyService which has just one method execute with two functions as parameters. The first parameter points to a request function and the second one points to a response function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19217e71c40925d09a024054a6def9e4/href">https://medium.com/media/19217e71c40925d09a024054a6def9e4/href</a></iframe><p>The service uses a so-called <a href="https://api.dart.dev/stable/2.10.4/dart-async/Completer-class.html">Completer</a> under the hood. Completers are objects that encapsulate the idea of finishing a long-running task at some later point. If you have a Completer, you can get a <a href="https://api.dart.dev/stable/2.12.0/dart-async/Future-class.html">Future</a> from it. When a task is finished or aborted, we can resolve or reject this Future by calling complete(data) or completeError(error) respectively. An example of the usage from my project looks like as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0c9bf7610b1d218ebda2baef9f39dab/href">https://medium.com/media/b0c9bf7610b1d218ebda2baef9f39dab/href</a></iframe><p>Note a keyword await in front of requestReplyService.execute(...). Two private methods _requestTrackPositions and _trackPositionRetrieved$ invoke the request and updatesFor methods from the MessagingService respectively.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f98d346b2a4a5f8f31132ce76e10332/href">https://medium.com/media/6f98d346b2a4a5f8f31132ce76e10332/href</a></iframe><p>That’s all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d727e33e4711" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[14 language features in TypeScript and Dart you may miss in Java]]></title>
            <link>https://olegvaraksin.medium.com/14-language-features-in-typescript-and-dart-you-may-miss-in-java-6bdc11c6fee7?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bdc11c6fee7</guid>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Tue, 08 Sep 2020 17:29:20 GMT</pubDate>
            <atom:updated>2020-09-08T17:29:20.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kq0vk7WJEWyxsJ0MPrXaaA.png" /></figure><p>As a full-stack developer, I have to switch between several programming languages in my day-to-day business: Java (backend), TypeScript (web dev) and Dart (mobile dev). In this blog post, I will try to demonstrate <strong>fourteen </strong>built-in language constructs in <a href="https://www.typescriptlang.org/">TypeScript</a> and <a href="https://dart.dev/">Dart</a> which convinced me to believe that these languages are more sophisticated and flexible than Java. You can already see in the picture above how fluent you can build collections in Dart using conditionals and repetition. These features are called “collection for” and “collection if”. Neat? But there are more. As you could also see, the type information in Dart is preserved at runtime. The check if the variable listOfStrings has the type List&lt;String&gt; works fine at runtime. In contrast, Java has <em>type erasure</em>, which means that generic type parameters are removed at runtime. In Java, you can’t test directly whether a collection is of type List&lt;String&gt;.</p><p>After reading this blog post, you will notice that people behind TypeScript and Dart spent much time in language design to make them user-friendly. In this article, we will cover:</p><ul><li>String interpolation</li><li>Multiline strings</li><li>Parameter properties in constructor</li><li>Optional parameters</li><li>Default parameter values</li><li>Null-aware operators</li><li>Spread operator</li><li>Indistinguishability of fields and getters / setters</li><li>Mixins (aka multiple inheritance)</li><li>Dynamic extensions of existing types</li><li>Asynchronous programming with async / await</li><li>Generators</li><li>Control flow analysis</li><li>Method chaining (amazing builder pattern!)</li></ul><blockquote>You can try all code snippets in <a href="https://www.typescriptlang.org/play/">TypeScript Playground</a> or <a href="https://dartpad.dev/">DartPad</a> respectively.</blockquote><h3>1. String interpolation</h3><p>String interpolation is a process of evaluating the final string by injecting a variable or an expression in a string literal.</p><h4>TypeScript</h4><p>The string interpolation is an ECMAScript 2015 (ES6) feature. It works by using${variable} or ${expression} syntax. An example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWAT46d5aceuSVdH_NLAOg.png" /></figure><h4>Dart</h4><p>In Dart, you can use $variable or ${variable} syntax for the string interpolation. The variable itself can be of any type. The expression in ${} can be used as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6E9qgOAYZvcpnSOF5W2GA.png" /></figure><blockquote>Dart internally calls toString() on objects that are being interpolated.</blockquote><p>Sure, in Java you can leverage String.format(...) but built-in language constructs in TypeScript and Dart are shorter and more concise.</p><h3>2. Multiline strings</h3><h4>TypeScript</h4><p>Multiline strings is an ES6 feature. They can be created with a backtick (`) at begin and end of a string. No + sign is necessary for string concatenation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDpk_bP_Sm6N_7JXIYy9lQ.png" /></figure><h4>Dart</h4><p>The Dart’s way to create a multiline string is a triple quote with either single or double quotation marks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMb0nx-yRJEhZolQ-L3mLg.png" /></figure><p>Furthermore, if you have two string literals, you do not need to use + to concatenate them. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04nh5HBkbrAYar0CVZdppQ.png" /></figure><h3>3. Parameter properties in constructors</h3><p>Parameter properties in constructors let you create and initialize a class member in one place.</p><h4>TypeScript</h4><p>Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly, or both. For example, instead of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XeGt2jbMc2kByhItWjVjNg.png" /></figure><p>just write</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ed_gxn3HbXAknFlqfJcxBA.png" /></figure><h4>Dart</h4><p>In Dart, this feature is called “initializing formals”. Just use the this. syntax before a constructor parameter. The main rule of <a href="https://dart.dev/guides/language/effective-dart/usage">effective Dart</a> is: do use initializing formals when possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*za607aLOeOM6sdbR_INNfA.png" /></figure><blockquote>Note that in Dart you can not omit the property declaration (see the code snippet above). But in Dart you can use ; instead empty constructor body{}.</blockquote><p>Saidy, but this simple and handy feature is missing completely in Java.</p><h3>4. Optional parameters</h3><p>Optional parameters are optional in that the caller isn’t required to specify a value for the parameter when calling a function.</p><h4>TypeScript</h4><p>In TypeScript, we can specify that a property (in interfaces / classes) or a parameter (in functions) is optional with a question mark (?) after the name. Optional parameters are especially handy in functions. An example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UA64il9qPGI9tlYyB-hTMA.png" /></figure><h4>Dart</h4><p>Optional parameters in Dart can be <em>named</em> and <em>positional</em>. A parameter wrapped by [ ] is a positional optional parameter. A parameter wrapped by { } is a named optional parameter. Named parameters can be referenced by names when invoking a function. Values for named parameters can be passed in any order, when invoking the function (this is the main benefit of them). The required parameters are listed first, followed by any optional parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_b_ubVhhIrslUlOLjNjfkA.png" /></figure><h3>5. Default parameter values</h3><p>An optional parameter can have a default value which is used when a caller does not specify a value. Such default values are provided after the = operator.</p><h4>TypeScript</h4><p>The TypeScript example above can be rewritten now as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n_gPVbxiQI9ZDLqfiwUctQ.png" /></figure><p>The function invocation at the default value’s position can be placed as well. By this way, the default value can be calculated at runtime.</p><h4>Dart</h4><p>The example with the optional parameter port can be rewritten as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gf30UiI_Afr_ngVQz1lfZA.png" /></figure><h3>6. Null-aware operators</h3><p>There are two null-aware operators which work almost similar in TypeScript and Dart and allow us to write a compact code.</p><ul><li>Optional chaining operator ?.</li><li>The logical nullish coalescing operator ??</li></ul><h4>TypeScript</h4><p>The optional chaining and nullish coalescing operators are new ECMAScript features. Optional chaining lets us write code where TypeScript can immediately stop running some expressions if we run into a null or undefined. Let&#39;s write a code snippet with and without the optional chaining operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hhDeYb7duIMkfhlTEt7YIg.png" /></figure><p>The nullish coalescing operator returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkmWH0dSST-dS1Z22VPuHA.png" /></figure><p>This is a new way to say that the value foo will be used when it&#39;s &quot;present&quot;; but when it&#39;s null or undefined, calculate bar() in its place. The above code is equivalent to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gU--3Q-gcmH-HGRyR5w7g.png" /></figure><h4>Dart</h4><p>In Dart, alle properties and variables are initialized with null per default (every type is an object). Use ?. when you want to call a method or access a property on an nullable object. If the object is null, the result of the method invocation or property accessing is also null. The syntax with the null-aware ?? operator is expr = expr1 ?? expr2.<strong> </strong>If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2. With null-aware operators you can do nice things like this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2ukc-9zSv1OBlQg92ab5g.png" /></figure><h3>7. Spread operator</h3><p>The syntax of the spread operator is three dots (...) followed by an iterable object. It expands the iterable object into individual elements.</p><h4>TypeScript</h4><p>The spread operator can be used to expand an array in a places where zero or more elements are expected. Using this, we can e.g. merge two or more arrays or objects. Examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LDyBJ9uYk20IegE6htCJfA.png" /></figure><h4>Dart</h4><p>The spread operator in Dart provides a concise way to insert multiple elements into a collection. You can use this operator to insert all elements of a collection into another collection. There is also a null-aware spread operator ...? which helps to avoid exceptions when to be inserted collection is null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwG3AhFiz9Hw2Hd9uBTtow.png" /></figure><h3>8. Indistinguishability of fields and getters / setters</h3><p>Getters and setters provide access to the properties of an object. In Java, it’s common to hide all fields behind getters and setters, even if the implementation just forwards to the field. Calling a getter method is different than accessing a field in Java. Getters and setters have different names than the corresponding field names. For example, if you have a field name, the getter would be getName() and the setter setName(String name). Just look at this example in Java:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FMvSZ5DxhWX_6lgA3rahoQ.png" /></figure><p>In TypeScript and Dart, the getters and setters have the same names as the corresponding fields. You can expose a field in a class and later wrap it in a getter and setter without having to touch any code that uses that field. We can say — fields and getters / setters are completely indistinguishable. Let’s look at code snippets in these languages.</p><h4>TypeScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzCZUwKVkA2QJtnn9UqBdw.png" /></figure><p>Please note, you don’t have to use the method here, just assign the value directly.</p><h4>Dart</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6ToscnWyZ1W0zRdg5Yj6A.png" /></figure><blockquote><a href="https://dart.dev/guides/language/effective-dart/usage">Effective Dart</a> recommends: DON’T wrap a field in a getter and setter unnecessarily.</blockquote><h3>9. Mixins</h3><p>Mixin is the process of combining multiple classes to a single target class. It is intended to overcome the limitations of single inheritance model. In Java, TypeScript an Dart, we can’t inherit or extend from more than one class with extends but mixins in TypeScript and Dart helps us to get around that. Mixins create partial classes which we can combine to form a single class that contains all the methods and properties from the partial classes. From a mathematical point of view, one can say that the classic, single super-class inheritance creates a tree (left picture). And mixin pattern creates a directed acyclic graph (right picture).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*NwDZVHnsJI0CDObUpEeuWA.png" /></figure><p>Composing partial behaviors with mixins in both languages is different.</p><h4>TypeScript</h4><p>Let’s create a Timestamped mixin that tracks the creation date of an object in a timestamp property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNS5PS2nHvcvv_Smajzkpg.png" /></figure><p>Let’s create a User class now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUdPn9dbdOZPjwj40CnaqQ.png" /></figure><p>Finally, we create a new class by mixing Timestamped into User.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qb0DDST7Chhs46Lp02vVQQ.png" /></figure><h4>Dart</h4><p>In Dart, we can use the with keyword on every class we want to extend with additional properties and behaviors. Assume, we have a class Person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZeOBjSqT2tDw9OQogrLFFg.png" /></figure><p>Let’s define a class Learner having one method learn() and a class Student which will extend Person and include everything from theLearner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_iqMS64nimhfIxDg84-uQ.png" /></figure><p>An instance of type Student can now access both methods info() (from Person) and learn() (from Learner).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bn2HJefICXrEZ7fIBKpfdw.png" /></figure><h3>10. Dynamic extensions of existing types</h3><p>Dynamic extensions are a way to add additional functionality to existing libraries without touching them. That means, if you have e.g. a class in a third-party library, you can extend it without changing the class or creating a subclass. This is a killer feature in my opinion which makes a language attractive. There is no something similar in Java at the time of writing.</p><h4>TypeScript</h4><p>TypeScript allows merging between multiple types such as interface with interface, enum with enum, namespace with namespace. This feature is called <em>declaration merging</em>. Declaration merging is when the TypeScript complier merges two or more types into one declaration provided the same name. Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QdCbJDACcMjeZt5DPKtBiw.png" /></figure><p>Why use declaration merging and where does it shine?</p><ul><li>You can extend declarations of third-party libraries that you import into your project.</li><li>You can extend declarations of generated TypeScipt definitions, which are usually coming from backend. In my project, we generate TypeScript code from plain Java objects by a Maven plugin.</li><li>TypeScript uses merging to get different types for the different versions of JavaScript’s standrad libraries. Example: the Array interface. It is defined in <em>lib.es5.d.ts</em> file. By default this is all you get. But if you add <em>ES2015</em> to the <em>lib</em> entry of your <em>tsconfig.json</em>, TypeScript will also include <em>lib.es2015.d.ts</em>. This includes another Array interface with additional methods like find that were added in ES2015. They get added to the other Array interface via merging.</li></ul><blockquote>One project where I was involved and used this technique: <a href="https://www.npmjs.com/package/@types/offscreencanvas">OffscreenCanvas by “Definitely Typed”</a> — the repository for high quality TypeScript type definitions.</blockquote><h4>Dart</h4><p>In Dart there is also a way to add functionality to existing libraries. This feature is called <em>extension methods</em>. The syntax is extension [&lt;Name&gt;] on &lt;Type&gt; {&lt;Methods&gt;}. The name after the keyword extension is optional. Let’s see some examples how to extend the type int.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7l3-VJlRa_yOnUBFhmUfg.png" /></figure><p>Now, we can directly call toBinaryString() on every integer. There are two implementations of the method str() — in this case, we should wrap an integer by the extension name to enables the unambiguous identification of the extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfD8nv52S8Hgoh8tuF27Vw.png" /></figure><p>Let’s see another example how to extend a generic List.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwkKDPf5opa94uw7tkIeyQ.png" /></figure><h3>11. Asynchronous programming with async / await</h3><p>A long time ago, an asynchronous behavior was modeled using callbacks. Having many nested callbacks led to so called <em>callback hell</em> or <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)">pyramid of doom</a>. An example (pseudo code):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmoVUB0BIkOZLpCaPVBf0w.png" /></figure><p>Problems with callbacks:</p><ul><li>Execution order is the opposite of the code order.</li><li>The code is hard to read.</li><li>Difficult to run requests in parallel.</li></ul><p>Later, many programming languages introduced much better concepts to deal with asynchronism. JavaScript introduced the concept of a <em>Promise </em>to break the pyramid of doom. A Promise represent something that will be available in the future. Dart has the concept of <em>Future</em>. A Future represents the result of an asynchronous operation. It is waiting for the function’s asynchronous operation to finish or to throw an error. If the asynchronous operation succeeds, the Future completes with a value.</p><p>What is about Java? Since Java 8 we have <em>CompletableFuture</em>. An example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyuBEgt9WcoFOQf5aFdQbQ.png" /></figure><p>The get method waits for the computation to complete, and then retrieves its result. Can we write this kind of code better? Yes, in TypeScript and Dart we can write it better with async and await.</p><h4>TypeScript</h4><p>ES2017 introduced the async and await keywords which allow to write the code in a synchronous manner. Anawait is used to wait for a promise to resolve or reject. It can only be used inside an async function. Let’s rewrite the psedo-code above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3fnDBAu81JH1YMfEhx33wA.png" /></figure><p>The await keywords pause execution of the fetchPages function until each Promise returned by fetch resolves.</p><h4>Dart</h4><p>Thanks to Dart’s feature async / await, you might never need to use the Future API directly. So, instead of</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ni03G0XpTHOK7bNntr_Tw.png" /></figure><p>you can write the code more straightforward</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qzuUU3VnMEXcST1KGHY5OQ.png" /></figure><blockquote>If you follow Dart’s best practice, the return value should be Future&lt;void&gt;.</blockquote><h3>12. Generators</h3><p><em>Generators </em>(<a href="https://dict.leo.org/englisch-deutsch/more">more</a> <a href="https://dict.leo.org/englisch-deutsch/precisely">precisely</a> <em>generator functions</em>) is a handy construct when you need to lazily produce a sequence of values. Both TypeScript and Dart have a built-in support of synchronous and asynchronous generators. With generators, we can create iterable objects where values come synchronously or asynchronously. A generator function is declared with an asterisk (*). A produced sequence of values is emitted with the yield keyword. In this blog post, I will only show how to use asynchronous generators.</p><h4>TypeScript</h4><p>If we execute a generator function, an object implementing <em>iterable </em>protocol is returned. The iterable protocol allows an object to be iterable. To iterate over such objects, we should use for … of or for await … of loop respectively. An asynchronous generator is an async function with asterisk. The function body contains one or more await operators. The await operator is used to wait for a promise to resolve or reject.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JQnc_msfpDZumlsuHJbDQ.png" /></figure><h4>Dart</h4><p>Dart has a similar concept as TypeScript. To implement an asynchronous generator function, mark the function body as async*, and use yield statements to deliver values. The return value is a Stream object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0koDyNsQ_xuSxDF5-tyvMw.png" /></figure><h3>13. Control flow analysis</h3><p>Both TypeScript and Dart have an excellent support for control flow analysis. The type checker analyses all possible flows of control in statements and expressions to produce <em>the most specific type</em> possible at any given location for a local variable or parameter. Let’s create three classes Pet, Dog and Cat in order to demonstrate the control flow analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2Qo3zRVRWqRQ56dXndauQ.png" /></figure><h4>TypeScript</h4><p>In TypeScript, you can create <em>user defined type guards</em>. User defined type guard is just a function that returns a type predicate in the form of someArgument is someType. If the function returns true, TypeScript will narrow the type, so that no cast is required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sLE_P_8CCS6PFa8U7m6EA.png" /></figure><p>As you can see, in the if-statement, we can call bark() without the cast to the Dog. The type of the foo was narrowed automatically by the TypeScript compiler.</p><h4>Dart</h4><p>To achieve the same result in Dart, we can use the type test operator is. It returns true if the object has the specified type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aJkEANeG1L7XAoiily-saA.png" /></figure><p>The Dart compiler narrows the type of the foo without the typecast as (as operator is used to cast an object to a particular type).</p><h3>14. Method chaining</h3><p>Method chaining allows you to apply a sequence of operations on the same object. Method chaining is often being used for building objects for classes having a lot of properties. A standard implementation of this approach in OOP languages is a <em>builder pattern</em>. Let’s implement a simple example in Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqfG89uW8jHx98wS7Gyu9Q.png" /></figure><p>By returning this, we can receive the class instance back immediately to call another method in the chain. There is a lot of code, even for this simple implementation without an inner public staticBuilder class (a popular implementation of the builder pattern). TypeScript and Dart can save your time and offer more elegant constructs here.</p><h4>TypeScript</h4><p>I like an implementation of the builder pattern with ES6 proxy. The Proxy object enables you to create a proxy for another object, which can intercept and redefine operations for that object. See <a href="https://javascript.info/proxy">an explanation</a> for more details. A generic implementation for every use case could be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MBvfkNNosTt5XI0urZ3Cvg.png" /></figure><p>The usage is simple. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v0U8iSrFSqKC3tq7nUDGMA.png" /></figure><p>For more advanced generic implementation look <a href="https://github.com/Vincent-Pang/builder-pattern">this project</a> on GitHub.</p><h4>Dart</h4><p>Dart has a cascaded method invocation. Instead of . notation, the cascade notation uses .. (double-dot) in order to access current modifying instance. Assume, we have a class User with setters / getters for most important fields. We can instantiate a User instance as follows with the cascaded method invocation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDkqSbbEzweTXWiIJQvDVg.png" /></figure><p>By using cascade, we don’t have to put many of repeated return this inside the class. But we can still return something else appropriate to the methods. Cascades can be nested as well. That allows even faster object buildings. See the <a href="https://dart.dev/guides/language/language-tour#cascade-notation-">example with nested cascades</a> from the Dart language tour. This feature saves you the steps of creating temporary variables and allows you to write more fluid code.</p><p>That’s all. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bdc11c6fee7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make Ionic Storage reactive]]></title>
            <link>https://olegvaraksin.medium.com/how-to-make-ionic-storage-reactive-acdd8996f1e6?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/acdd8996f1e6</guid>
            <category><![CDATA[ionic-framework]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[ionic-storage]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 13:59:33 GMT</pubDate>
            <atom:updated>2019-04-04T14:02:12.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBl31NVXuoKdDiEFj9LScw.png" /></figure><p><a href="https://ionicframework.com/docs/building/storage">Ionic Storage</a> offers a LocalStorage-like API and can be configured for various storage engines. It also allows to persist many types of data, e.g. strings, numbers and blobs. The default order of storage engines which are tried to be used (from top to bottom):</p><ul><li>SQLite (file-based database on native devices)</li><li>IndexedDB</li><li>WebSQL</li><li>LocaleStorage</li></ul><p>It depends on the availability of concret storage engine if it will be used or not. IndexedDB, as data storage in browser, should be preferred over LocaleStorage because it offers asynchronous read / write operations and doesn’t block the main thread. LocaleStorage blocks the main thread with its sync read / write operations.</p><p>For storage engines in the web, Ionic Storage is backed by <a href="https://localforage.github.io/localForage/">LocaleForage</a> — a well-known offline storage implementation. LocaleForage API is <strong>Promise</strong> based. If you read, write or remove values through this API, you will always get an ES6 Promise. It’s no wonder that the API of Ionic Storage is Promise based too. Sometimes though, we wish us a reactive API, especially if we develop an Angular application with RxJS. RxJS is a key player that can make the Ionic Storage API reactive. In this blog post, I will show main steps to achieve this goal. For demonstration purpose, only three values will be made persistent:</p><ul><li>“authToken” — JWT Authentification-Token</li><li>“deviceId” — some UUID which identifies the client device.</li><li>“trackNumber” — number of rail track :-)</li></ul><h4>Ad-hoc solution</h4><p>A quick &amp; dirty solution is straightforward. We just have to implement a service class which communicates with Ionic Storage and reveals set-, get- und remove-operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/123dd24e8b2dae1a164efd225ff2aef4/href">https://medium.com/media/123dd24e8b2dae1a164efd225ff2aef4/href</a></iframe><p>This implementation doesn’t fit all use cases well.</p><h4>Do it right!</h4><p>Let’s do it reactive. We will start with a simple Redux-like store implemented with Angular. I’ve borrowed the idea from this brilliant blog post: <a href="https://jurebajt.com/state-management-in-angular-with-observable-store-services/">State management in Angular with observable store services</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22780fd6237d0ff5ace7f7b7a1729782/href">https://medium.com/media/22780fd6237d0ff5ace7f7b7a1729782/href</a></iframe><p>BehaviorSubject keeps the last state. The state itself is a plain object with three properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf99b58cc127950e53a95490a391907a/href">https://medium.com/media/cf99b58cc127950e53a95490a391907a/href</a></iframe><p>A concrete implementation of the abstract Store class above leverages the Ionic Storage under the hood. Updating some value in the persistent store (IndexedDB or whatever) reflects in the Redux-like store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/adbe4f8c92b2721c7683ab5e42edaf92/href">https://medium.com/media/adbe4f8c92b2721c7683ab5e42edaf92/href</a></iframe><p>The ready$ Promise is useful if you have to wait until all values are read from the persistent storage (we will see an example below). Let’s show some usages of this reactive store implementation (which is backed by the Ionic Storage as you could see above). The first example demonstrates a facade class which injects CoreStore. The facade is a mediator between UI components and underlying services. It decouples presentation and business / service layers. As you can see, we can grab RxJS streams from the store. Such streams can be used directly in Angular templates with async pipe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eac76f106cf0725b6856072bf6aefb2e/href">https://medium.com/media/eac76f106cf0725b6856072bf6aefb2e/href</a></iframe><p>The next example shows an Angular Guard which checks if the user is logged in or not. It reads authToken and redirects the user to the login page if the token was not set (is undefined).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9bdd1d8fb537eb9c931b80719dd0ef3/href">https://medium.com/media/d9bdd1d8fb537eb9c931b80719dd0ef3/href</a></iframe><p>The last example is a component where the user inputs the track number. It is an excerpt for the sake of simplicity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42dcb5f016dd9e8bf4eb60f39fcccace/href">https://medium.com/media/42dcb5f016dd9e8bf4eb60f39fcccace/href</a></iframe><p>That’s all. Have fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acdd8996f1e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pluggable Angular UI (Part I)]]></title>
            <link>https://olegvaraksin.medium.com/pluggable-angular-ui-part-i-7497f42c429f?source=rss-140b4b117d7c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7497f42c429f</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[pluggable]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Oleg Varaksin]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 19:37:49 GMT</pubDate>
            <atom:updated>2019-03-10T19:37:49.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kT8xCfak9ygpI6Va0Ir8Ug.png" /></figure><p>In this blog post, I would like to share my thoughts how to build a pluggable Angular Frontend with modules which you can combine together like a puzzle. Modules should not know each other — that means, they don’t have cross-dependencies. Modules should be lazy loaded at runtime by means of backend configuration which specifies what modules your UI has exactly. In other words, the functionality scope depends on the logged in user, more exactly on the user role, such as “customer”, “developer”, etc. You got the idea.</p><p>In the first part, I will explain the bootstrapping process of such lazy loaded modules. In the second part, I will try to describe how the modules communicate. This inter-module communication happens by so called <em>extension points </em>— a well-known concept (design pattern) from the <a href="https://wiki.eclipse.org/FAQ_What_are_extensions_and_extension_points%3F">Eclipse RCP</a> world. In the picture above, you see a diagram from my current web project called “SSP UI”. There is a core module. This is a core part doing bootstrapping. The core module is always present in the application. Every other separate module may reference this core module. The core module on his part doesn’t know about specific code of separate modules (no references) because such modules are loaded at runtime. Otherwise, the project would not be compilable.</p><p>The first step is to create separate chunks for all available modules which can potentially be lazy loaded. This task can be accomplished in angular.json file. The lazyModules section contains paths to all available Angular’s module files. Example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f86739e386b08f236a6bddd4ce0e6048/href">https://medium.com/media/f86739e386b08f236a6bddd4ce0e6048/href</a></iframe><p>Netanel Basal has already blogged about how to load non-routable modules in Angular: “<a href="https://netbasal.com/the-need-for-speed-lazy-load-non-routable-modules-in-angular-30c8f1c33093">The Need for Speed: Lazy Load Non-Routable Modules in Angular</a>”. He used a special loader — SystemJsNgModuleLoader and explained very well how to load modules by components. In his example, a modules’ root component was created and injected dynamically. But how to lazy load modules with providers? Imagine, you have a lot of services (and probably no components) in your modules which you want to instantiate with the help of the Angular dependency injection. Well, first, you need some configuration file where you reference modules in a similar manner as in the <a href="https://angular.io/guide/lazy-loading-ngmodules">routes with loadChildren</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38c0c11806b1c1569838eca356416385/href">https://medium.com/media/38c0c11806b1c1569838eca356416385/href</a></iframe><p>Second, you need a service, say ConfigurationService, in order to be able to load the configuration. The configration should be loaded <strong>before</strong> the application is completely initialized. Angular has a special provider token for that — APP_INITIALIZER. Note, the factory method returns a Promise. Once the Promise is resolved, Angular starts the bootstrapping process.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ba3d7951ded323ff75041a19fc36f15/href">https://medium.com/media/4ba3d7951ded323ff75041a19fc36f15/href</a></iframe><p>The service itself looks like as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d0a908d85a0c471f53a168ebac00e6a/href">https://medium.com/media/8d0a908d85a0c471f53a168ebac00e6a/href</a></iframe><p>The loaded configuration is saved in this service. In the module classes, we need two static fiels: components and providers. The first one lists components shipped with the module (if any). The second one lists providers and their dependencies (other providers in constructors) in the same syntax as Angular does it. A typical module looks like as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e2f1ae0253f6d55af178439b746ef7a/href">https://medium.com/media/1e2f1ae0253f6d55af178439b746ef7a/href</a></iframe><p>The main AppComponent uses the Facade Pattern. Note, that we’re doing the shutdown work within the window’s beforeunload callback. Why not in ngOnDestroy? Because ngOnDestroy only works when the route is changed. We also need the root injector for our main goal— bootstrapping providers of lazy loaded modules.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a09b423b03c829e772bdc87e5a0b9aae/href">https://medium.com/media/a09b423b03c829e772bdc87e5a0b9aae/href</a></iframe><p>The facade utilizes the ModuleLifecycleService which I will show in a moment. This service exposes two methods: bootstrapApplication and shutdownApplication. The first method returns a boolean Promise notifying the caller if all modules could be successfully loaded or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ffa6e2bcc6c13198c0cf7f8abce1597/href">https://medium.com/media/2ffa6e2bcc6c13198c0cf7f8abce1597/href</a></iframe><p>Take a breath at this point and look how the app logs lazy loaded modules with providers and components :-)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8YAwnk3vobXOZFCXZoRNxA.png" /></figure><p>After this short pause, we continue our adventure. Let’s define two interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18ea2ee44483f3e4ddf98f977fd066d2/href">https://medium.com/media/18ea2ee44483f3e4ddf98f977fd066d2/href</a></iframe><p>The bootstrapApplication method in the ModuleLifecycleService accesses the mentioned above configuration. Every NgModuleFactory is loaded through the NgModuleFactoryLoader. Here is the full code. We’re going to discuss the handling of module factories shortly after you have looked into the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/220eadb6ef13f507aae0cef940cf44f2/href">https://medium.com/media/220eadb6ef13f507aae0cef940cf44f2/href</a></iframe><p>For every module factory we’re doing repetitive handling:</p><ul><li>Create NgModuleRef by means of the root injector. NgModuleRef <a href="https://angular.io/api/core/NgModuleRef">represents an instance of an </a><a href="https://angular.io/api/core/NgModuleRef">NgModule</a>. We need it in the next steps.</li><li>Check if the module has components (remember the static field components?). If it’s true, a ComponentFactory is created and saved in the model. The ComponentFactory is needed later if you would like to create the corresponding component dynamically. See <a href="https://angular.io/api/core/ComponentFactory">Angular documentation</a> for more details.</li><li>Check if the module has providers (remember the static field providers?). If it’s true, the providers are registered and instantiated programmatically. This can be completed with the help of Injector.create(providers: StaticProvider[], parent?: Injector). See <a href="https://angular.io/api/core/Injector#create">Angular documentation</a> for more details.</li></ul><p>If you make a mistake in the configuration, e.g. a typo in the module’s path or name, you will face an exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*9FiLpKnH-EN36HysfCbuIQ.png" /></figure><p>If a module has no providers, it’s a little bit strange. Right? In this case, you will face a warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*eVaZd5qV7KPx-1uAdtPekg.png" /></figure><p>That’s all. Stay tuned, the second part with extension points is coming soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7497f42c429f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>