Examples for 'rlang::new_weakref'


Create a weak reference

Aliases: new_weakref

Keywords: experimental

### ** Examples

e <- env()

# Create a weak reference to e
w <- new_weakref(e, finalizer = function(e) message("finalized"))

# Get the key object from the weak reference
identical(wref_key(w), e)
[1] TRUE
# When the regular reference (the `e` binding) is removed and a GC occurs,
# the weak reference will not keep the object alive.
rm(e)
gc()
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  696458 37.2    1099998 58.8  1099998 58.8
Vcells 1307577 10.0    8388608 64.0  2227318 17.0
identical(wref_key(w), NULL)
[1] TRUE
# A weak reference with a key and value. The value contains data about the
# key.
k <- env()
v <- list(1, 2, 3)
w <- new_weakref(k, v)

identical(wref_key(w), k)
[1] TRUE
identical(wref_value(w), v)
[1] TRUE
# When v is removed, the weak ref keeps it alive because k is still reachable.
rm(v)
gc()
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  696595 37.3    1099998 58.8  1099998 58.8
Vcells 1307121 10.0    8388608 64.0  2227318 17.0
identical(wref_value(w), list(1, 2, 3))
[1] TRUE
# When k is removed, the weak ref does not keep k or v alive.
rm(k)
gc()
          used (Mb) gc trigger (Mb) max used (Mb)
Ncells  696617 37.3    1099998 58.8  1099998 58.8
Vcells 1307160 10.0    8388608 64.0  2227318 17.0
identical(wref_key(w), NULL)
[1] TRUE
identical(wref_value(w), NULL)
[1] TRUE

[Package rlang version 1.1.4 Index]