Q:

Magento 2 : How to Clear Previous Messages in MessageManager

I have added a below line in my observer file for the event checkout_cart_save_after
$this->_messageManager->addNotice(__("A Notice Message"));

Every time it hits observer, it displayes more than 1 message in frontend. I need to display only one message at a time. Can anyone pls help to clear the messages in message manager?
My observer logic is below:
 public function execute(Observer $observer)
    {
        allowCheckout = 1;
          //custom logic......
         if($allowCheckout == 0){
           $this->_messageManager->addNotice(__("A Notice Message"));

         }

    }

So Everytime when the event occurs it goes to observer and displays message manager notice message. It displays more than one message. I want only once the message to be displayed

A:

Try the following code:
$this->_messageManager->getMessages(true); //this will clear your messageManager container
$this->_messageManager->addNotice(__("A Notice Message"));

