Mostrando postagens com marcador observable. Mostrar todas as postagens
Mostrando postagens com marcador observable. Mostrar todas as postagens

Difference between Promise and Observable

The main difference between "Promise" and "Observable" is in the nature of the operations they represent.

Promise

- Single Value: Represents a single value that may be available now, in the future, or never.
- Non-Cancelable: Once a "Promise" is resolved or rejected, it cannot be cancelled.
- Error Handling: Uses the ".then()" method to handle success and the ".catch()" method to handle failures.

Promise Example:

const promiseExample = new Promise((resolve, reject) => {
   // simulates an asynchronous operation
   setTimeout(() => {
     const success = true;

     if (success) {
       resolve("The operation was completed successfully!");
     } else {
       reject("The operation failed!");
     }
   }, 2000);
});

promiseExample.then((result) => {
   console.log(result); // success: the operation was completed successfully!
}).catch((error) => {
   console.error(error); // failed: the operation failed!
});

Observable

- Multiple Values Over Time: Can represent a sequence of values emitted over time.
- Cancellable: Can be canceled manually, allowing greater control over the life cycle.
- Event Handling: Uses methods as ".subscribe()" to react to events and manipulate emitted values.

Observable example:

import { Observable, Observer } from 'rxjs';

const observableExample = new Observable((observer: Observer<string>) => {
   // simulates a sequence of values emitted over time
   let count = 0;
   const interval = setInterval(() => {
     observer.next(`Value ${count}`);
     count++;

     if (count > 3) {
       observer.complete(); // indicates that the sequence has been completed
       clearInterval(interval);
     }
   }, 1000);

   // cleanup when canceling subscription
   return () => clearInterval(interval);
});

const subscription = observableExample.subscribe(
   (value) => console.log(value), // handles emitted values
   (error) => console.error(error), // handle errors
   () => console.log('The sequence was completed') // handles sequence completion
);

// unsubscribe after 5 seconds
setTimeout(() => {
   subscription.unsubscribe();
}, 5000);

In summary, while "Promise" is better suited for representing single success or failure operations, "Observable" is more powerful when you are dealing with sequences of events or data over time, as HTTP requests, user events, etc. In many cases in Angular, asynchronous operations are represented as "Observable", especially when they involve continuous data streams.

Observable in Angular

The Observable pattern is an essential reactive programming part and is widely used in Angular. Observables are an implementation of the Observer pattern, which allows an object (the "observable") to send notifications to a list of observers (the "subscribers") when changes or events occur.

In the Angular context, Observables are often used to handle asynchronous streams of data, as user events, HTTP request handling, and state updates. Here are some key concepts related to the Observable pattern in Angular:

1. Observable

An Observable represents a sequence of events that can include values, errors, and completion notifications. It provides methods to "observe" these events.

2. Subscriber

A Subscriber is a function or object that observes an Observable. It defines how to respond to events emitted by the Observable.

3. Operators

Operators are functions that act on an Observable and return a new Observable. They are used to perform transformations and manipulations on the data emitted by the Observable.

4. Creating Observables

Observables can be created from event sources like button clicks, HTTP requests, and others. Additionally, you can create Observables manually using constructors such as "new Observable(observer => { /* Observable logic */ })".

Using Observables in Angular Basic Example

Let's consider a simple example where a service provides asynchronous data using an Observable:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

@Injectable({
   providedIn: 'root'
})
export class MyService {
   getAsynchronousData(): Observable<string[]> {
     // simulates an asynchronous HTTP request
     return of(['Data 1', 'Data 2', 'Data 3']);
   }
}

And in an Angular component, you can subscribe to this Observable to receive the data:

import { Component, OnInit } from '@angular/core';
import { MyService } from './my-servico.service';

@Component({
   selector: 'app-my-component',
   template: `
     <h2>Data:</h2>
     <ul>
       <li *ngFor="let item of data">{{ item }}</li>
     </ul>
   `
})
export class MyComponent implements OnInit {
   data: string[];

   constructor(private myService: MyServiceService) {}

   ngOnInit() {
     this.myService.
getAsynchronousData().subscribe(
       (data) => {
         this.data = data;
       },
       (error) => {
         console.error('Error getting data:', error);
       }
     );
   }
}

In this example:
  • "getAsyncronousData()" returns an Observable simulating an asynchronous request.
  • In the component, we use subscribe to listen for data when it is ready and react to it.

Observables in Angular are a fundamental part of the framework's reactive approach, providing a consistent way to handle asynchronous operations and data flows. Observables are widely used in several areas, as event handling, communication between components, and HTTP request management.

How to communicate between Components in Angular

In angular, there are several ways to communicate between components. The approach choice depends on the relationship between the components (if they are at the same level, if one is the father or child) and the specific application requirements. Below are some of the main ways to communicate between angular components:

1. Communication by Inputs and Outputs

Inputs ("@input"): A father component can pass data to a child component using the "@input" directive.

Example (Child Component)
import { Component, Input } from '@angular/core';

@Component ({
   selector: 'app-child',
   template: `<p> {{message}} </p>`
})
export class ChildComponent {
   @Input() message: string;
}

Example (Father Component)
import { Component } from '@angular/core';

@Component ({
   Selector: 'app-father',
   Template: `<app-child [message]="fatherMessage"></ app-child>`
})
export class FatherComponent {
   fatherMessage = 'Hello, Child!';
}

Outputs ("@output"): A child component can issue events for the father component using the "@output" directive.

Example (Child Component)
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
  @Output() messageSent = new EventEmitter<string>();

  sendMessage() {
    this.messageSent.emit('Hello, father!');
  }
}

Example (Father Component)
import { Component } from '@angular/core';

@Component({
  selector: 'app-father',
  template: `<app-child (messageSent)="receiveMessage($event)"></app-child>`
})
export class FatherComponent {
  receiveMessage(message: string) {
    console.log(message); // 'Hello, father!'
  }
}

2. Shared services

A service can be used to share data and features between components that do not have a direct parent relationship.

Example (Service)
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class ShareDataService {
  sharedMessage = 'Message shared between components.';
}

Example (Component)
import { Component } from '@angular/core';
import { ShareDataService } from './share-data.service';

@Component({
  selector: 'app-component',
  template: `<p>{{ sharedMessage }}</p>`
})
export class ComponentComponent {
  sharedMessage: string;

  constructor(private shareService: ShareDataService) {
    this.sharedMessage = shareService.sharedMessage;
  }
}

3. Observables and Subjects

Observables and Subjects can be used to implement a publication and subscription standard for communication between components.

Example (Service)
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class ComunicationService {
  private messageSubject = new Subject<string>();
  message$ = this.messageSubject.asObservable();
  sendMessage(message: string) {
    this.messageSubject.next(message);
  }
}

Example (Components)
import { Component, OnDestroy } from '@angular/core';
import { ComunicationService } from './comunication.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-component1',
  template: `<button (click)="sendMessage()">Send Message</button>`
})
export class Component1Component {
  constructor(private comunicationService: ComunicationService) {}

  sendMessage() {
    this.comunicationService.sendMessage('Component 1 Message');
  }
}

@Component({
  selector: 'app-component2',
  template: `<p>{{ receivedMessage }}</p>`
})
export class Component2Component implements OnDestroy {
  receivedMessage: string;
  private subscription: Subscription;

  constructor(private comunicationService: ComunicationService) {
    this.subscription = this.comunicationService.message$.subscribe(
      message => (this.receivedMessage = message)
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

These are some of the common approaches for communication between angular components. The choice of approach depends on the architecture of its application and the specific communication requirements between components.

HashMap in Java

Let’s break down how   HashMap   works internally (Java 8+ implementation). What Is a HashMap? HashMap<K, V>  is a  hash table–based  ...