title: Cleanup when `global.R` variables are deleted
body: <h1>Question</h1>
  
  <p>From the documentation it is clear, that variables in <code>server.R</code> have a different life span than the ones in <code>global.R</code>.</p>
  
  <p>For cleanup operations in <code>server</code>, there is the <code>session$onSessionEnded</code> callback function. An example to use this can be found <a href="https://stackoverflow.com/questions/23276491/how-to-implement-a-cleanup-routine-in-r-shiny">here</a>.</p>
  
  <blockquote>
    <p>Is there something similar for the <code>global.R</code> script?</p>
  </blockquote>
  
  <h1>Context</h1>
  
  <p>In my setup, I have two variables with reference semantics (instances of <code>R6</code> classes) in the global scope that need cleanup. The cleanup operation is dependend on both objects. Some pseudocode.</p>
  
  <pre><code># context global.R
  # -----------------------------------------------------------------------------------------
  
  A = classA$new()
  B = classB$new()
  
  # call after the last sesion has ended
  cleanupFunction = function(){
    # call this before B$finalize()
    A$saveToSQL(B)
    A$finalize()
  }
  </code></pre>
  
  <p><code>A</code> and <code>B</code> are both operaing on <code>server.R</code>.</p>
  
  <hr>
  
  <h1>Current workaround</h1>
  
  <p>Since both <code>classA</code> and <code>classB</code> are <code>R6</code> classes, I have access to the <code>finalize</code> method (a destructor in <code>C++</code> terms). So the following workaround is possible.</p>
  
  <pre><code>classA$finalize = function(){
    if(cleanupFlag){
      cleanupFunction()
      cleanupFlag &lt;&lt;- FALSE
    }
  }
  
  classB$finalize = function(){
    if(cleanupFlag){
      cleanupFunction()
      cleanupFlag &lt;&lt;- FALSE
    }
  }
  </code></pre>
  
  <p>This requires me to use callbacks already because of scoping.</p>
  
  <hr>
  
  <p>If someone knows a "proper" way to solve this, I would be very interested.</p>