Libetia A

Libetia A

1564795658

Using Subjects To Multicast Observers In RxJS

RxJS is a framework for reactive programming that makes use of observables, which makes it really easy to write asynchronous code.

According to the official documentation, this project is a kind of reactive extension to JavaScript with “better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface.”

It is the official library used by Angular to handle reactivity, converting pull operations for callbacks into observables.

Prerequisites

To be able to follow this article’s demonstration, you should have:

  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with Node installation)
  • Angular CLI version 7.0
  • The latest version of Angular (version 7)

Confirm that you are using version 7 using the command below, and update to 7 if you are not.

// run the command in a terminal
ng version

Download this tutorial’s starter project here to follow through the demonstrations. Unzip the project and initialize the Node modules in your terminal with this command:

npm install

What are RxJS subjects?

RxJS subjects are observables that also act as observers and provide a platform for data values to be multicasted to more than one observer. An observable can be defined simply as a function that returns a stream of data values to one observer over time.

A subject is a kind of advanced observable that returns values to more than one observer, which allows it to act as a kind of event emitter.

Why are RxJS subjects important?

First of all, it is an observable, so all the methods available for use with observables automatically work with subjects. The additional fact that you can multicast, which means that more than one observer can be set for a subject, is really awesome.

Observables act purely as producers, but subjects can be both producers and consumers, shifting the reach of observables from unicast to multicast. Subjects should be used in place of observables when your subscriptions have to receive different data values. With multicasting, it matches each subscription to its respective observer.

RxJS subject syntax

Inside an Angular project, the syntax for defining an RxJS subject looks like this:

import { Subject } from "rxjs";
ngOnInit(){
const subject = new Subject();
}

Demo

To illustrate RxJS subjects, let us see a few examples of multicasting. If you started reading this post from the start, you will have the starter project open in your VS Code application. Open your app.component.ts file and copy the code below into it:

import { Component, OnInit } from '@angular/core';
import { Subject } from "rxjs";
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  ngOnInit(){
   const subject = new Subject();

subject.subscribe({
next: (data) => console.log('First observer prints '+ data)
});

subject.next(1);
subject.next(2);
}
}

You’ll see that unlike the observable, which requires a kind of helper module passed to create it, the subject just needs a new subject construct, and with that, you can go ahead and use it just as you would any observable. If you run the app in development with the dev command:

ng serve

You will see that it logs data values just as we’d expect, emulating a fully functional observable. This means that both the error and the complete values can be passed to the observer.

Working with more than one observer

Remember that one of subjects’ main features is their ability to have more than one observer set that can make reference to it. You will see that in action with the same logic as we have above. Copy the code block below into the app.component.ts file:

import { Component, OnInit } from ‘@angular/core’;
import { Subject } from “rxjs”;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit{
ngOnInit(){
const subject = new Subject();
subject.subscribe({
next: (data) => console.log('First observer prints '+ data)
});
subject.next(1);
subject.subscribe({
next: (data) => console.log(‘Second observer prints ‘+ data)
});
subject.next(2);
subject.next(3);
}
}

If you save the file and it recompiles, you will notice that although there are two observers for the subject, the various observers still return data values as expected.

If you notice, the second observer did not receive the very first next value because the subject simultaneously holds and efficiently distributes the values according to scope and definition. This is the beauty of using subjects in RxJS.

Subject variants

There are officially three variants of RxJS subjects. They are:

  • Behavior subject
  • Replay subject
  • Async subject

Behavior subject

The behavior subject is a very special type of subject that temporarily stores the current data value of any observer declared before it. Here is a clear illustration — copy the code below into your app component file:

import { Component, OnInit } from ‘@angular/core’;
import { BehaviorSubject } from “rxjs”;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.css’]
})
export class AppComponent implements OnInit{
ngOnInit(){
const subject = new BehaviorSubject(0);
subject.subscribe({
next: (data) => console.log('First observer prints '+ data)
});
subject.next(1);
subject.next(2);
subject.subscribe({
next: (data) => console.log(‘Second observer prints ‘+ data)
});
subject.next(3);
}
}

Here you see that the behavior subject is imported from RxJS, and the new construct must take in an initial value (which was zero in our case). Also, unlike the prior illustration, you see that the very last data value before the new observer was called (the current value 2) was stored and then reported by the new observer even though it was defined after the reference to it.

This is exactly what the behavior subject achieves: storing and then passing on the current data value to the new observer.

Replay subject

After viewing the possibilities that comes with the behavior subject variant, any curious person might ask why they can’t store more than the current value. Well, the good news is that with the replay subject, you can. So the replay subject is basically the behavior subject with the option to choose how many values you want to emit from the last observer. Here is a quick example:

import { Component, OnInit } from ‘@angular/core’;
import { ReplaySubject } from “rxjs”;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.css’]
})
export class AppComponent implements OnInit{
ngOnInit(){
const subject = new ReplaySubject(2);
subject.subscribe({
next: (data) => console.log('First observer prints '+ data)
});
subject.next(1);
subject.next(2);
subject.subscribe({
next: (data) => console.log(‘Second observer prints ‘+ data)
});
subject.next(3);
}
}

Here it is specified that only one last value be emitted from the last observer, so the output in your browser console should be exactly the same save for the initial log line.

Additionally, this replay subject can take an optional second argument called window time, recorded in milliseconds. It just allows you to time the return.

Async subject

This is the very last variation. It acts exactly the same as the behavior subject but can only execute after a complete method is called. Remember there are three methods that an observable can call: next, error, and complete. So this particular variation emits the very current value only when it sees the complete method call.

import { Component, OnInit } from ‘@angular/core’;
import { AsyncSubject } from “rxjs”;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [’./app.component.css’]
})
export class AppComponent implements OnInit{
ngOnInit(){
const subject = new AsyncSubject();
subject.subscribe({
next: (data) => console.log('First observer prints '+ data)
});
subject.next(1);
subject.next(2);
subject.subscribe({
next: (data) => console.log('Second observer prints '+ data)
});
subject.next(3);
subject.complete();
}
}

If you run this in your development server, your browser console will look like this:

Conclusion

This is an introductory overview of subjects in RxJS and how important they are in your workflow. There were also illustrations and even explanations of the three variations that subjects come in. Now you can start to use them in your Angular projects.

Thanks for reading. If you liked this post, share it with all of your programming buddies!

Further reading

☞ Angular 8 (formerly Angular 2) - The Complete Guide

☞ Angular & NodeJS - The MEAN Stack Guide

☞ The Complete Node.js Developer Course (3rd Edition)

☞ The Web Developer Bootcamp

☞ Best 50 Angular Interview Questions for Frontend Developers in 2019

☞ MEAN Stack Angular 8 CRUD Web Application

☞ How to build a CRUD Web App with Angular 8.0

☞ MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

☞ An Introduction to Web Workers

☞ JavaScript Web Workers: A Beginner’s Guide

☞ Using Web Workers to Real-time Processing

☞ How to use Web Workers in Angular app

Using Web Workers with Angular CLI


#angular #angular-js #web-development

What is GEEK

Buddha Community

Using Subjects To Multicast Observers In RxJS

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

RxJS Basics in Examples

Let’s take a look at simple examples of using RxJS, and after that, I hope, you will get the basic idea behind it.

What will be covered in this article:

  • 1. Simplest example
  • 2. Observer
  • 3. Observable
  • 4. Subscription
  • 5. RxJS API List: “index” functions:
  • 5.1 concat
  • 5.2 merge
  • 5.3 forkJoin
  • 5.4 fromEvent
  • 5.5 iif
  • 5.6 defer
  • 6. Http requests using “ajax”

#subscription #observer #asynchronous #rxjs #observables

Nat  Grady

Nat Grady

1621428060

Angular Meets RxJS: Higher-order Observables

Introduction

This article belongs to a series called “Angular meets RxJS” in which I try to explain reactive programming using “RxJS” in an “Angular” context the best I can.

Table of contents

Basic concepts

RxJS subjects

RxJS operators (Part 1)

RxJS operators (Part 2)

RxJS operators (Part 3)

“takeUntil” and the “async” pipe

Higher-order observables

Error handling

RxJS schedulers (coming soon)

Mini-project: Build a Pokedex (coming soon)

In this article

As we saw in the article about  “RxJS” operators, a higher-order function in “JavaScript” is a function accepting another function in parameter or returning one. The same concept exists for observables. In this article, we are going to see why it is absolutely critical to understand them and how you can use them to simplify and secure your pipelines.

The situation

Let’s take a common situation as a basis for this article. Say you’re building a “Medium” clone to allow people to write some articles. A very nice feature of “Medium” is that it autosaves your document at regular interval.

To simulate the REST API, I’ll use the “json-server” npm package. If you don’t know it, it’s a very useful package that provides a REST API based on a “JSON” file.

Below are the steps required to set it up, you can skip these if you don’t want to replicate the examples of this article on your computer.

Start by installing “json-server” globally by running the command:

yarn global add json-server

Once this is done, create a file called “db.json” with the following content:

{
    "documents": [
        {
            "id": "1",
            "lastUpdate": null
        }
    ]
}

#observables #angular #rxjs #javascript

Coy  Roberts

Coy Roberts

1600835077

Observables in RxJS: How to Use Javascript Observables

Observables are a pioneering concept in Reactive Programming. Observables are data source wrappers and then the observer executes some instructions when there is a new value or a change in data values. The Observable is connected to the observer who does the execution through subscription, with a subscribe method the observer connects to the observable to execute a code block.

If you do not know what is Reactive Programming, then check out my article on this website What is ReactiveProgramming in Javascript.

We will see following topics in this article.

  1. What is an observable?
  2. Difference between Observable and Promise
  3. Difference between Array and Observable
  4. Creating an observable
  5. Unsubscribe from an observable

What are Observables in Javascript

Observables are simply data streams or collections which arrive at a time. Observables are objects that can notify subscribers when the change is happening. We can wrap Observables as an object which contains the following things.

  1. Data Streams
  2. Some methods (next(), error(), complete())

Observables in RxJS

#observables #javascript #reactive programming

What is Ansible? A Tool to Automate Parts of Your Job

Hello everyone, today we will talk about Ansible, a fantastic software tool that allows you to automate cross-platform computer support in a simple but effective way.

Table of Contents

  • What is Ansible?
  • How Does Ansible Work?
  • Ansible's Architecture
    • Plugins
    • Modules
    • Inventories
    • Playbook
  • Benefits of Using Ansible
  • Why is Ansible so important?
  • How to Install and Configure Ansible on Ubuntu
  • Conclusion
  • References

What is Ansible?

Ansible is a tool that generates written instructions for automating IT professionals' work throughout the entire system infrastructure.

It's designed particularly for IT professionals who use it for application deployment, configuration management, intra-service orchestration, and practically anything else a systems administrator does on a weekly or daily basis.

Ansible is simple to install because it doesn't require any agent software or other security infrastructure.

While Ansible is at the cutting edge of automation, systems administration, and DevOps, it's also valuable as a tool for devs to use in their daily work.

Ansible allows you to set up not just one machine but a complete network of them all at once, and it doesn't require any programming knowledge.

How Does Ansible Work?

Ansible connects to nodes on a network (clients, servers, etc.) and then send a little program called an Ansible module to each node.

It then runs these modules through SSH and deletes them once they're done.

Your Ansible control node must have login access to the managed nodes for this interaction to work.

The most frequent method of authentication is SSH keys, but alternative methods are also allowed.

If you want to see how to install and start using Ansible, we'll cover that below.

Ansible's Architecture

Now let's take a look at Ansible's architecture and how it manages operations.

Ansible Plugins

Plugins are supplementary pieces of code that enhance functionality, and you've probably used them in many other tools and platforms. You can use Ansible's built-in plugins or create your own.

Examples are:

  • Action Plugins
  • Become Plugins
  • Cache Plugins
  • Callback Plugins
  • Cliconf Plugins
  • Connection Plugins
  • HTTP API Plugins
  • Inventory Plugins
  • Lookup Plugins
  • Netconf Plugins
  • Tests

Ansible Modules

Modules are short programs that Ansible distributes to all nodes or remote hosts from a central control workstation. Modules control things like services and packages and can be executed via playbooks.

Ansible runs all of the modules needed to install updates or complete whatever operation is required and then removes them after they're done.

Ansible Inventories

Ansible uses an inventory file to track which hosts are part of your infrastructure and then accesses them to perform commands and playbooks.

Ansible works in parallel with various systems in your infrastructure. It accomplishes this by picking methods mentioned in Ansible's inventory file, which is saved in the host location by default.

Once the inventory is registered, you can use a simple text file to assign variables to any of the hosts, and you may retrieve inventory from a variety of sources.

Ansible Playbook

IT professionals can use Ansible playbooks to program applications, services, server nodes, and other devices without starting from scratch. Ansible playbooks, along with the conditions, variables, and tasks included within them, can be stored, shared, and reused forever.

Ansible playbooks function similarly to task manuals. They're simple YAML files, a human-readable data serialization language.

Playbooks are at the heart of what makes Ansible so popular. They specify activities that can be completed quickly without requiring the user to know or remember any specific syntax.

Benefits of Using Ansible

  • Ansible is quick and easy to use, as it runs all of its operations over SSH and doesn't require the installation of any agents.
  • Ansible is a free, open-source tool, and it's straightforward to set up and use: Ansible's playbooks don't require any special coding knowledge.
  • Ansible can be used to perform simple tasks such as ensuring that a service is operating or rebooting from the command line without the need for configuration files.

In a more extensive or more uniform system, Ansible may be a better fit. It also provides a set of modules for managing various methods and cloud infrastructure.

Why is Ansible so important?

Modernization and digital transformation require automation that's both necessary and purposeful. We need a new management solution in today's dynamic contexts to increase speed, scale, and stability throughout IT infrastructure.

Technology is our most potent instrument for product improvement. Previously, accomplishing this required a significant amount of manual labor and intricate coordination. But today, Ansible - a simple yet powerful IT automation engine used by thousands of enterprises to simplify their setups and speed DevOps operations - is available.

How to Install Ansible on Ubuntu

Run the following commands to configure the PPA on your machine and install Ansible:

Update the repository:

sudo apt-get update

Install the software properties:

sudo apt-get install software-properties-common

And then install Ansible like this:

sudo apt-add-repository --yes --update ppa:ansible/ansible

Then run this:

sudo apt-get install ansible

You should have something similar to what is shown below:

ansible_installation

Now that you have successfully installed Ansible, let's test if it's working by using the command below:

ansible --version

ansible_check

We'll use the command below to instruct Ansible to target all systems for the inventory host localhost, and we'll run the module ping from your local console (rather than ssh).

ansible all -i localhost, --connection=local -m ping

You should get a response similar to what you can see below:

ansible_ping

How to modify the hosts that Ansible targets

We'll make changes to the host's file in /etc/ansible/hosts. This is the default file where Ansible searches for any defined hosts (and groups) where the given commands should be executed remotely.

sudo nano /etc/ansible/hosts

Add the lines below to the file and save the modifications:

[local]
localhost

Execute this command with your adjusted inventory file:

ansible all --connection=local -m ping

The response should look similar to what we have below:

ansible_pong

How to configure a remote server

We deploy our Ansible test program to our remote server using a Digital Ocean droplet.

Use the command below to ssh into the server:

ssh username@IP_Address

Note: we have already configured an ssh key in our profile, which was selected when creating the droplet.

ansible_server

How to configure Ansible for a remote server

We will edit our hosts file in /etc/ansible/hosts using the command below:

sudo nano /etc/ansible/hosts

Add the lines below to the file and save the modifications:

[remote]
remote_test

[remote:vars]
ansible_host=IP_ADDRESS_OF_VIRTUAL_MACHINE
ansible_user=USERNAME

To see if Ansible can connect to your remote compute instance over SSH, let's type the following command:

ansible remote -m ping

asnible_result

We'll make an Ansible playbook using the command below, which is the typical way of telling Ansible which commands to run on the remote server and in what order. The playbook is written in .yml and follows a strict format.

In the official Ansible documentation, you can learn more about playbooks.

nano my-playbook.yml

Add the following code, which tells Ansible to install Docker in several steps:

---
- name: install docker
hosts: remote
become_method: sudo
become_user: root
vars: #local variables
docker_packages:
- apt-transport-https
- ca-certificates
- curl
- software-properties-common

tasks:
- name: Update apt packages
become: true #make sure you execute the task with sudo privileges
apt: #use apt module
update_cache: yes #equivalent of apt-get update

- name: Install packages needed for Docker
become: true
apt:
name: "{{ docker_packages }}" #uses our declared variable docker_packages
state: present #indicates the desired package state
force_apt_get: yes #forces to use apt-get

- name: Add official GPG key of Docker
shell: curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

- name: Save the current Ubuntu release version into a variable
shell: lsb_release -cs
register: ubuntu_version #Output gets stored in this variable

- name: Set right Docker directory
become: true
shell: add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ubuntu_version.stdout }} stable"

- name: Update apt packages
become: true
apt:
update_cache: yes

- name: Install Docker
become: true
apt:
name: docker-ce
state: present
force_apt_get: yes

- name: Test Docker with hello world example
become: true
shell: docker run hello-world
register: hello_world_output

- name: Show output of hello word example
debug: #use debug module
msg: "Container Output: {{hello_world_output.stdout}}"

We can now execute it with the command below:

ansible-playbook my-playbook.yml -l remote

After that, we'll see some magic happen (it might take a while), and somewhere in the last debug message in our terminal, we should see "Hello from Docker!"

Conclusion

In this article, we had a detailed look into Ansible, its benefits, how it works and what it can do, its architecture, plugins, playbook, inventory, and how to configure and deploy Docker with Ansible on a remote server.

Thank you for reading!

Link: https://www.freecodecamp.org/news/what-is-ansible/

#ansible