getOrPut method

T getOrPut(
  1. T value
)

Returns the current value associated with this LocalThread, or stores and returns value if no value has been set yet.

This is a convenient helper that ensures a value always exists for the current Isolate.
If the value is already present, it is returned unchanged.
If the value is absent, value is stored using set and then returned.

Example

final local = ThreadLocal<int>();

print(local.get()); // null

// Sets the value because none exists yet.
final first = local.getOrPut(42);
print(first); // 42

// Returns the existing value without overwriting it.
final second = local.getOrPut(99);
print(second); // 42

Returns the existing or newly stored value.

Implementation

T getOrPut(T value) {
  final bucket = isolateLocalValueStore.getBucket<T>(Isolate.current, _key);
  final result = bucket.get();

  if (result != null) {
    return result;
  }

  set(value);
  return value;
}