Executing a method of a custom entity after all instances have been built I'm putting together a private message module. Conversations threads are a custom entity within the module. A thread can potentially appear twice on a page - once in the 'inbox' (a block), and once as the main content of the page. I'm wrapping the rendered threads with a div that I'm attaching in an override of EntityViewBUilder::view(). If the user has not viewed the thread, I'm adding a class of 'unread-thread' to the div wrapper.

Where I'm running into a problem, is finding a place to mark the thread as 'read'. If I do it at the end of EntityViewBuilder::view(), then the class is only applied to the first instance of the thread on the page, since it's already been marked read by the time it comes to the next instance of the thread on the page. I want the class to be part of the wrapper on all instances of the thread on the page.

So I need to find somewhere to mark a thread as read, but only after all instances on the page have passed through EntityViewBuilder::view(). I'm thinking a post-render hook may be good, but I'm not finding one. Does anyone have any suggestions?
You can use an event for this, a RESPONSE event with a low priority or a TERMINATE event. See for example UserRequestSubscriber::onKernelTerminate:

/**
   * Updates the current user's last access time.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The event to process.
   */
  public function onKernelTerminate(PostResponseEvent $event) {
    if ($this-&gt;account-&gt;isAuthenticated() &amp;&amp; REQUEST_TIME - $this-&gt;account-&gt;getLastAccessedTime() &gt; Settings::get('session_write_interval', 180)) {
      // Do that no more than once per 180 seconds.
      /** @var \Drupal\user\UserStorageInterface $storage */
      $storage = $this-&gt;entityManager-&gt;getStorage('user');
      $storage-&gt;updateLastAccessTimestamp($this-&gt;account, REQUEST_TIME);
    }
  }