No shows on the free webinars

Yesterday, I was a No Show at one of the FREE webinars that I registered for. To be honest with you, even when I was registering for this event two weeks ago, I was not sure if I’d be able to attend due to potential scheduling conflicts. I was thinking to myself, “I’m interested in this topic, and if it will be video recorded, the organizers will send the link to the video to all people who registered”. The organizers sent me a reminder a day before the event and the URL for attending right before the event.

Needless to say that one of my meetings at work ran longer than expected and I didn’t attend the webinar. This is not the first time I was a No Show.

Now let’s look at it from the other side of the fence. Periodically, I run free webinars myself, and I noticed the same thing – only a fraction of the registered participants would actually attend the event. For such webinars, I use a paid GoToMeeting subscription that allows up to 50 participants to attend.

So I decided to monitor the numbers to decide at what number of registrants should I close RSVPs. I started closing RSVPs when 55 people would register. About 20 would actually show up. Then I kept increasing the number of allowed RSVPs, and today I believe that with my 50-participant subscription, I can close RSVP when the number of registrants is anywhere between 100 and 150, in other words, 2 to 3 times more than available seats.

I’m not blaming anyone, and I’m not apologizing for my own no shows. It is what it is. On the other hand, I almost never had cancellations or no shows in the events I charged for. Money talks!

Categories Web

TypeScript generics and animal workers

I’ve been using Java generics for years, and when I saw their syntax in TypeScript, I simply put a checkmark in the list of TypeScript features that I already know and understand.I was wrong. Let me show you something.

Below is a Java code sample that illustrates the use of generics. I’ve created a class Person and its subclass Employee. Then I created a standalone class Animal. Finally, I used the generic notation to ensure that if anyone would try to add an instance of Animal to the collection of workers, the Java compiler would complain, and it did:

Then I re-wrote the same program in TypeScript, and its compiler didn’t complain:

But if I’ll comment out the property name in the class Animal, the TypeScript compiler will complain:

This may lead to the following conclusions:

1. In TypeScript, if you use a type as a parameter in generics, it’ll allow any other type as long as it has the same properties (e.g. Person.name and Animal.name)
2. In TypeScript, animals can be workers

If there is something in TypeScript documentation that has different explanations to this behavior, please let me know. Generics is an interesting subject and I’ll write another blog soon.

Yarn package manager: yarn.lock

Yesterday, I was running yet another Angular workshop. After explaining how to install dependencies using npm, I show how to use Yarn (see this blog), a faster alternative to npm, and suggest that the students should consider using Yarn.

Before the workshop, I give handouts with several projects to the group and then ask the group to open a particular project, install the dependencies and run the app. Usually, everything goes smoothly, but this time many people started to complain about a runtime error. In this app, I was using themes from Angular Material 2, but the app couldn’t find the file “node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css”.

I was strange. I tested all the projects two days before the class. After checking the content of the node_modules directory on Paul’s computer, I couldn’t find even the directory node_modules/@angular/material/core let alone that CSS file.

Then I asked if everyone gets this error? Everyone except Jim got this error. Jim was using Yarn for installing dependencies while everyone else was using npm. After learning this, I guessed what was the problem.

I’ using Yarn too, and all my projects included the file yarn.lock, which is created after the initial install storing all packages and their versions there were installed for the project. When you do the yarn install next time, it checks if the file yarn.lock is present, it installs exactly packages of those versions that were listed in yarn.lock. This file can be checked into the version control repo used by your team to ensure that everyone would have exactly the same dependencies.

Now let me explain what happened in the classroom. The package.json in that project included the dependency

"@angular/material": "^2.0.0-beta.2"

The file yarn.lock in that project had the following:

"@angular/material@^2.0.0-beta.2":
  version "2.0.0-beta.2"
  resolved "https://registry.yarnpkg.com/@angular/material/-/material-2.0.0-beta.2.tgz#65ee8733990347b7518b7f42113e02e069dc109b"

Hence, when Jim ran his Yarn install, he got Angular Material 2 2.0.0-beta.2, which had the file “node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css”

But last week, a new version (Beta.3) of Angular Material 2 has been released with a breaking change – they rearranged the file structure:

So the students who didn’t use Yarn, got the latest version while my project used “the old” location of that CSS file.

Fixing this issue in the app was an easy task, but I wanted you to appreciate that Yarn gives you predictability in the projects that have multiple dependencies. Some library author introduces a breaking change, and your app gives a runtime error.

After fixing the CSS location in the app, I deleted my yarn.lock file and re-ran the install. The newly created yarn.lock has this fragment:

"@angular/material@^2.0.0-beta.2":
  version "2.0.0-beta.3"
  resolved "https://registry.yarnpkg.com/@angular/material/-/material-2.0.0-beta.3.tgz#ec31dee61d7300ece28fee476852db236ded1e13"

The first line indicates the dependency as it was listed in my package.json, and the second line shows the actual version that has been installed. Now my project is working again… until the next breaking change.

Angular CLI: multiple apps in the same project

You may need to have an Angular project that has multiple apps so you can run the build of a particular app, say depending on the customer you’re preparing the build for. In my case, I wanted to create a project with multiple apps that I use in my Angular workshops. Having a single project with multiple apps allows you to run a time-consuming npm or yarn install once and just modify the name of the app you want to run.

For example, you may have multiple versions of the main bootstrap file that load different root modules. The file .angular-cli.json has the apps section with the property main, and to run a particular app, I’d instruct the students to modify .angular-cli.json to point at a particular app, e.g. "main": "main1.ts". To run another app, I’d instruct them to change this line to "main": "main2.ts".

But then I figured out that you can configure multiple apps in the same .angular-cli.json and run the build for a particular app by name. The apps property is an array, and you just need to configure each app there. For example, the following fragment shows how I configured two applications – app1 and app2 in the same .angular-cli.json:

"apps": [
    { "name":"app1",
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main-resolver.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css",
       "../node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    },
    { "name":"app2",
      "root": "src",
      "outDir": "dist2",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main-luxury.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "styles.css",
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],

Now to bootstrap the app main-resolver.ts I run the following command:

ng serve --app app1

To bootstrap the main-luxury.ts, I run this:

ng serve --app app2

You can also refer to each app by its index in the apps array:

ng serve --app 0
or
ng serve --app 1

The option –app is available for the ng build command as well. The following screen shot shows my project after I built the app1 into dist and app 2 into dist2.

This is a pretty useful Angular CLI feature and I wanted to share my findings with you.

RX: Reactive Libraries

Over the last several years, the term “reactive programming” became popular in many programming languages. Reactive Manifesto was published although it gives a rather generic definition of reactive systems http://www.reactivemanifesto.org. Yes, an app should response fast (Responsive), remain functional in case of errors (Resilient), be flexible in regards to increasing/decreasing computational resources (Elastic), and be based on asynchronous events (Message Driven).

Declaring the principles is a good start, but how to apply these principles in a concrete app? Let’a talk about reactive extensions libraries available for many programming languages.

About seven years ago, Erik Meijer from Microsoft created Reactive Extensions (Rx) – a set of libraries Rx.NET for processing asynchronous event-driven data streams. For example, someone posted a tweet and you received an immediate notification.

A non-reactive way of receiving tweets would be visiting twitter.com every now and then and reload the page hoping that one of the people you follow posted a new tweet – this is known as polling. The load on the server will substantially increase if every user will keep polling the server. The push model is a lot more efficient – just subscribe to the tweeter feed and get the tweets asynchronously pushed to you as they become available.

An online auction is another use case for the async data push. A user bids on the product, but other users may overbid her. Bids should be implemented as a stream that allows subscription so the users won’t need to constantly check if their offers are still the winning ones.

Another example is a stream on stock prices during the working ours of a stock exchange. Or take a stream of signals from a sensor (e.g. an accelerometer in your phone). Even the process of dragging the mouse over the screen can be treated as a stream of coordinates of the mouse pointer.

Five years ago, Microsoft released Rx.NET as an open source project. People liked it and the library was ported to other programming languages: RxCpp, RxJS, RxPHP, Rx.rb, Rx.py, RxJava, RxSwift, RxScala, RxKotlin.

Disclaimer. This post is not a Rx tutorial, but a brief introduction of the main Rx players. I work with RxJS and RxJava, but in this post, I’ll be using code samples in JavaScript

Let’s get familiar with the main concepts of Rx libraries, but first consider this non-reactive code:

int a1 = 2;

int b1 = 4;



int c1 = a1 + b1;  // c1 = 6

    

a1 = 55;           // c1 = 6, but should be 59    
b1 = 20;           // c1 = 6, but should be 75

After the execution of this code, c1 is still equal to 6. Sure enough, we could add more code to recalculate c1 after the values of both a1 and b1 changed, but a more proper way to handle this is by making c1 to be immediately recalculated as soon as either a1 or b1 change as in Excel spreadsheet. In other words, it would be nice to switch to the push model, where the new and asynchronously changed values are pushed to their consumer. We want to move away from the pull model, where the consumer is constantly asking the producer, “Do you have something new for me?… How about now?… Maybe now you have something?”

Observable, Observer, Subscriber

The main players of any Rx library are Observable, Observer, and Subscriber.

* Observable – an object or a function that emits sequences of data over time (a.k.a. producer)

* Observer – an object or a function that knows how to process the sequences of data (a.k.a. consumer)

* Subscriber – an object or a function that connects an Observable with Observer(s)

After looking at this diagram, many software developers will say, “We already know this. This is a pub-sub messaging with the implementation of the Observer pattern.” To some extent, this is correct, but there’s more to it:

1. Rx is meant for the asynchronous non-blocking data processing.

2. Rx offers a simple API with dedicated channels for sending data, errors, and the end-of-stream signal.

3. Any Rx library has about a hundred operators that can be applied to the data stream en route. Operators are easily composable.

4. Some of the Rx implementations (e.g. RxJava2) support the backpressure well. This is a scenario when a producer emits data faster than a consumer can handle.

5. You don’t need special messaging servers to use a Rx library. Everything you need is a part of your app.

6. In languages that support multi-threading, working with threads as well as switching between the threads is easier.Android developers will appreciate this because the UI rendering has to be done in the main thread while the calculation in others.

So how an Observable sends the data to the Observer? An Observer can implement three methods (their names may slightly vary depending on the language you use):

* next() – here’s a new value from the stream
* error() – here’s an error happened in the stream
* complete() – the stream’s over

In the next code sample, the function getData() turns the array with beers into an Observable and returns it back. Returns to whom? To the subscriber, when some other code invokes subscribe(). A subscriber – getData().subscribe(myObserver) – passes an Observer, as an argument to the function subscribe(). Accordingly, an Observer can implement three functions:

* Handling the next element from the stream
* Handling the stream error
* Handling the end of stream, if needed

// Defining the function that returns an Observable
function getData(){

    var beers = [
        {name: "Stella", country: "Belgium", price: 9.50},
        {name: "Sam Adams", country: "USA", price: 8.50},
        {name: "Bud Light", country: "USA", price: 6.50},
        {name: "Brooklyn Lager", country: "USA", price: 8.00},
        {name: "Sapporo", country: "Japan", price: 7.50}
    ];

// The observer will be provided at the time of subscription
    return Rx.Observable.create( observer => {

              beers.forEach( beer => observer.next(beer));
              observer.complete();
           }
    );
}

// Calling the function that subscribe to the observable
// The function subscribe() receives the Observer, represented by three functions
getData()
     .subscribe(
         beer  => console.log("Subscriber got " + beer),   // handling the arrived data
         error => console.err(error),                      // an error arrived
            () > console.log("The stream is over")         // the signal that the stream completed arrived
);

Our Observer consists of three fat arrow functions (=>). This syntax was introduced in the ECMAScript 6 spec. Our fat arrow callbacks may be invoked only after we invoked subscribe(). You can see this code sample in action here (open the browser’s console and click on the Run button).

Operators

Operators are functions that can transform the stream data between the moments when the Observable sent them and the function subscribe() received them. In other words, we can transform the data en route. Rx libraries have lots of operators.

Each operator is a function that takes an Observable as an argument, transforms (or ignores) it, and returns another Observable. Since the input and output of any operator have the same type, you can chain them up. Here’s how you can filter out the beer that’s more expensive than 8 dollars and convert the instances of the Beer object into strings.

Studying Rx operators require a time investment, and I’m planning to write more about them. The RX docs often include marble diagrams that help in understanding what a particular operator does. As an example, the marble diagram for the filter operator looks as follows:

On top, the incoming stream (an Observable) is represented by various geometrical shapes. Then the filter operator ignores every element but circles, and the resulting Observables will contain only the circles. When you look at the circle, visualize beers that are cheaper than eight dollars.

Still, how to make c1=a1+b1 reactive?

First, convert a1 and b1 into streams, for example:

const a1 = Rx.Observable.from([2, 55]);

But this stream will shoot 2 and 55 instantaneously, so let’s add the time dimension. To emulate a delay you can use another stream that just emits sequential numbers and join it using the zip operator with the stream that emits 2 and 55:

const a1 = Rx.Observable.from([2, 55])
  .zip(Rx.Observable.interval(1200), x => x);

When someone subscribes to a1, it’ll emit 2 and in 1.2 seconds 55. Similarly, let’s create a stream for b1 but with a delay of 1.5 seconds. Then, using streams composition and the operator combineLatest, we combine streams a1 and b1 and add their latest values. The entire code will look as follows:

const a1 = Rx.Observable.from([2, 55])
  .zip(Rx.Observable.interval(1200), x => x);
  
const b1 = Rx.Observable.from([4, 20])
  .zip(Rx.Observable.interval(1500), x => x);

a1.combineLatest(b1, (x, y) => x + y)
  .subscribe(val => console.log("c1=" + val));

To see this code in action, visit the Plunker at http://bit.ly/2nphn0k, open the browser’s console and click on the button Run. you’ll see how c1 is recalculated as soon as either a1 or b1 is changing.

If you haven’t worked with reactive libraries, take a look at the one available for your programming language and start using it in a real-world project.

A word of caution. Rx libraries allow you to write less code, but the code readability suffer. The person who reads the code needs to know Rx as well.

On the positive side, Rx libraries don’t require you to change the architecture of the entire project. Use them where you can make the async data to flow through a sequence of algorithms (think operators).

Update In the beginning of this post I made a statement that this blog is not a tutorial, but after reading one of the comments, I decided to add a link to the video of my recent presentation in New York at BuzzJS. During the first 25 min of this presentation, I was using just RxJS.

Categories Rx

Angular 4: Changes in the router

Angular 4 comes with some useful changes in the router. Let’s take a look at the changes in receiving parameters by a route and in the CanDeactivate guard (see here).

A route can receive the parameters either using a snapshot property of the ActivatedRoute or by subscribing to its property param. Now there is a property paramMap that allows you to either get a particular parameter by using the method get() or get all parameters by invoking getAll().

Here’s how to receive a parameter id that’s not changing in the parent:

export class ProductDetailComponentParam {
  productID: string;

  constructor(route: ActivatedRoute) {
    this.productID = route.snapshot.paramMap.get('id');
  }
}

If the parameter id is changing in the parent (as described here), you can subscribe to the stream of id’s as follows:

export class ProductDetailComponentParam {
  productID: string;

  constructor(route: ActivatedRoute) {

    route.paramMap.subscribe(
     params => this.productID = params.get('id')
     );
  }
}

The CanDeactivate guard now allows you to be more specific and conditionally prohibit navigating from a route depending on where the user is planning to navigate. The interface CanDeactivate now has an optional parameter nextState, which you can check to decide if you want to prohibit the navigation or not. The next code snippet shows the guard that would display a warning popup only if the user is trying to navigate to the home route represented by the path ‘/’. The navigation to any other routes remains unguarded.

@Injectable()
export class UnsavedChangesGuard implements CanDeactivate<ProductDetailComponent>{

    constructor(private _router:Router){}

    canDeactivate(component: ProductDetailComponent, 
                  currentRoute: ActivatedRouteSnapshot,
                  currentState: RouterStateSnapshot, 
                  nextState?: RouterStateSnapshot){

        let canLeave: boolean = true;

        // If the user wants to go to home component
        if (nextState.url === '/') {
          canLeave = window.confirm("You have unsaved changes. Still want to go home?");
        }
        return canLeave;

    }
}

Angular 4 was just released and there might be some other goodies in the router, but I just wanted to share with you these convenient additions.

Upgrading to the latest Angular CLI

As of the Angular CLI beta 30, the command to install Angular CLI looks as follows:

npm install -g @angular/cli

To get rid of the old version of Angular CLI and install the new one, run the following commands:

npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli

To update the existing CLI projects, modify the CLI dev dependency in package.json to this:

"@angular/cli": "1.0.0-beta.32"

Then update the CLI version on top of the angular-cli.json, remove your node_modules dir and run npm install.