1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.base.supplier; 6 7 import androidx.annotation.Nullable; 8 9 import org.chromium.base.Callback; 10 11 /** 12 * Wraps a lazy-loaded nullable object, notifying observers a single time when the dependency 13 * becomes available. This intentionally doesn't extend {@link OneshotSupplier} to support the 14 * supplied value being null. 15 * 16 * @param <T> The type of the wrapped object. 17 */ 18 public interface LazyOneshotSupplier<T> { 19 /** 20 * Add a callback that's called when the object owned by this supplier is available. If the 21 * object is already available, the callback will be called at the end of the current message 22 * loop. 23 * 24 * @param callback The callback to be called. 25 */ onAvailable(Callback<T> callback)26 void onAvailable(Callback<T> callback); 27 28 /** 29 * Returns the value currently held or <code>null</code> when none is held. Use {@link 30 * #hasValue} to tell if the value is intentionally null. 31 */ 32 @Nullable get()33 T get(); 34 35 /** Returns whether the supplier holds a value currently. */ hasValue()36 boolean hasValue(); 37 38 /** 39 * Creates a supplier using a lambda closure to hold onto the given value. Should only be used 40 * when the value already exists or in tests, as otherwise it defeats the purpose of the lazy 41 * part of this supplier. 42 */ fromValue(T value)43 static <T> LazyOneshotSupplier<T> fromValue(T value) { 44 return new LazyOneshotSupplierImpl<>() { 45 @Override 46 public void doSet() { 47 set(value); 48 } 49 }; 50 } 51 52 /** 53 * Allows callers to inline a lambda to satisfy the implementation of this object. The supplier 54 * must be able to run and complete synchronously at any point. 55 */ 56 static <T> LazyOneshotSupplier<T> fromSupplier(Supplier<T> supplier) { 57 return new LazyOneshotSupplierImpl<>() { 58 @Override 59 public void doSet() { 60 set(supplier.get()); 61 } 62 }; 63 } 64 } 65