Magento – How to get updated cart subtotal in checkout_cart_product_add_after event observer in Magento 2

cartevent-observermagento2totals

I want to add a free product to cart with another product. For that I wrote checkout_cart_product_add_after event observer. My problem is, I don't get the updated cart subtotal(after adding first product, it returns subtotal as 0). This is my observer code.

namespace StwBuyXGetY\BuyXGetY\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;

class AddfreeProduct implements ObserverInterface
{
    protected $_productRepository;
    protected $_cart;
    protected $formKey;
    public function __construct(
        \Magento\Checkout\Model\Cart $cart, 
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Form\FormKey $formKey){
        $this->cart = $cart;
        $this->formKey = $formKey;
        $this->logger = $logger;
    }
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $totals = $this->cart->getQuote()->getTotals();
        $subtotal = $totals['subtotal']->getValue();  
        $this->logger->debug($subtotal);
    }

}

enter image description here

enter image description here

Any help will be greatly appreciated.

Best Answer

We should use \Magento\Checkout\Model\Session:

/**
 * @var \Magento\Checkout\Model\Session
 */
protected $_checkoutSession;

public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession,
    .....
)
{
    $this->_checkoutSession = $checkoutSession;

}

Try to get the totals:

//Get totals
$this->_checkoutSession->getQuote()->getTotals();
//Get sub total.
$this->_checkoutSession->getQuote()->getSubtotal();