1. Shut it Down
If an R6 object connects to a database or a file,
2. teapot
then it can be dangerous to delete it
3. teapot
without making sure that you close the connections first. Similarly, if the R6 object has any side effects such as changing global options or global plotting parameters, then it is good practise to return those settings back to their previous state.
You've already learned
4. initialize()
how to define an initialize method to allow custom behavior when an object is created. initialize has a counterpart named finalize that allows custom behavior when an R6 object is destroyed.
5. thing_factory
Here's a Thing template with a private field named a_field.
The initialize method allows the field to be set when Thing objects are created.
finalize is always a function with no arguments, defined in the public element of an R6 class. The logic can be anything you like; in this case it simply prints a message explaining that the object has been finalized.
6. a_thing
To see how it works, let's create a Thing object.
When you delete the thing, the finalize method isn't called immediately. That happens when the object is garbage collected by R's memory management system. You can force this to occur by calling the gc function.
7. library(RSQLite)
A more realistic example would be a database manager object. When the object is created, a connection to the database is opened by the initialize method. Then when the object is destroyed, the connection is closed by the finalize method.
8. Summary
To summarize, R6 objects have a method called finalize that is used to clean up when the object is destroyed. It is useful for R6 objects that connect to databases or files, since it is important that the connections eventually get closed. finalize is called when the object is garbage collected by R.
9. Let's practice!