Skip to main content
4 of 4
added 107 characters in body
Kuba
  • 137.7k
  • 13
  • 289
  • 751

Keep in mind it is a toy answer, from my tests it appears it is not general enough.


MMA is well designed to fix problems it creates :)

What I've found is that Dynamic aren't stable but Initialization triggers as it should. Let's use it to overwrite it's content when new session occurs:

restartProtect[Dynamic[DateString[], UpdateInterval -> 1]]

restartProtect[Dynamic[DateString[], UpdateInterval -> 1]]

Dynamic[DateString[], UpdateInterval -> 1]

Dynamic[DateString[], UpdateInterval -> 1]

After restart only first two lines will still work.

Here's the code:

restartProtect[expr_] := DynamicModule[{session = $SessionID},
  expr
  ,
  SynchronousInitialization -> False,
  Initialization :> (
      If[
      session =!= $SessionID
          ,
          SetOptions[
              EvaluationNotebook[], 
              DefaultDuplicateCellStyle -> "Output"
          ];
          NotebookWrite[
              EvaluationBox[],
              BoxData @ ReplacePart[
                  NotebookRead[EvaluationBox[]], {1, 1, 2} -> $SessionID
              ]
          ];
          SetOptions[
              EvaluationNotebook[], 
              DefaultDuplicateCellStyle -> "Input"
          ]
       ]
  )
 ]
Kuba
  • 137.7k
  • 13
  • 289
  • 751