Imagine you are cooking pasta and sit down to play Dota 2, or any other game. You listen with one ear to see if the "dish" does not boil away. In this case, you are an observer. When the pasta starts to boil away — the event "pasta_began_to_boil_away" is triggered, which causes you (the observer) to rush to the kitchen (perform an action, an algorithm).

In Magento 2, as in real life, there are observers and events that are implemented on the basis of the "Publish-subscribe pattern". We have already described  plugins in Magento 2, which allows you to extend and change the functionality of the store. Let's see how you can do this with the help of events and observers in Magento 2.

Events 

Events are triggered by Magento 2 modules when an action has occurred or has to occur. Magento has many native events and also allows you to call your own event.

Use the dispatch method of the \Magento\Framework\Event\ Manager class to call an event.

For example:

namespace MyCompany\MyModule;

class MyClass{
    /**
    * @var EventManager
    */
    private $eventManager;
    public function __construct(
// some other dependancies
        \Magento\Framework\Event\Manager $eventManager
) {
//some code
        $this->eventManager = $eventManager;
    }
    public function something()
    {
        $eventData = null;
/* calling event 1 */
        $this->eventManager->dispatch('my_module_event_before');
        // some code
        /* calling event 2 */
        $this->eventManager->dispatch('my_module_event_after', ['myEventData'=>$eventData]);
   }
}

In this example, we called 2 events: "my_module_event_before" and "my_module_event_after". Observers should join the events by such names.

The second parameter in the dispatch method helps to pass the data array that will be available to the observer during its actions.

Observers

The observers in Magento 2  are certain types of classes that implement Magento\Framework\Event\ObserverInterface interface. The observer's code is executed as a result of the event call.

For example, to create an observer for the event of adding a product to the cart, which is called in the Magento\Checkout\Model\Cart class:

$this->_eventManager->dispatch(
'checkout_cart_product_add_after',
['quote_item' => $result, 'product' => $product]
);

1. Create an observers file in your module folder:

Observer/СheckoutСartProductAddAfter.php

with the following code:

<?php
namespace MyCompany\MyModule\Model;
use Magento\Framework\Event\ObserverInterface;
class СheckoutСartProductAddAfter implements ObserverInterface
{
public function __construct()
{
//Declaration of dependencies
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
/* We obtain oberver data using "getters" */
$product = $observer->getProduct();
$item = $observer->getQuoteItem();
/* Альтернативна версія "гетера"
$product = $observer->getData('product');
$item = $observer->getData('quote_item');
*/
//The code to execute at the event
}
}

The class name (in the example CheckoutCartProductAddAfter) can be different, but with the necessary requirements of PHP class names and the Magento 2 style code. Name the class so that its name immediately indicates the event in which it is used.

execute is the mandatory name of the method required by the interface.

2. Connect the observer to the event.

Create the following file in your module folder:

etc/events.xml

Add this code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_product_add_after">
<observer name="mymoduile_checkout_cart_product_add_after" instance="MyCompany\MyModule\Model\СheckoutСartProductAddAfter" />
</event>
</config>

You can create this file using etc/frontend/events.xml or etc/adminhtml/events.xml, depending on the scope. XML configurations created directly in the etc folder are used both in the storefront (frontend) and in the admin panel (adminhtml). 

3. Clear the cache.

Run the CLI command:

php bin/magento cache:clean