1 // Copyright 2020 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 * OneshotSupplier wraps an asynchronously provided, non-null object {@code T}, notifying 13 * observers a single time when the dependency becomes available. Note that null is the un-set 14 * value; a fulfilled supplier will never have a null underlying value. 15 * 16 * <p>This allows classes dependent on {@code T} to be provided with a 17 * OneshotSupplier during construction and register a {@code Callback<T>} to be notified when the 18 * needed dependency is available, but without the need to un-register that Callback upon 19 * destruction. Contrast to {@link ObservableSupplier}, which requires un-registration to prevent 20 * post-destruction callback invocation because the object can change an arbitrary number of times. 21 * 22 * 23 * <p>This class must only be accessed from a single thread. Unless a particular thread designation 24 * is given by the owner of the OneshotSupplier, clients should assume it must only be accessed on 25 * the UI thread. 26 * 27 * <p>If you want to create a supplier, see an implementation in {@link OneshotSupplierImpl}. 28 * 29 * <p>For classes using a OneshotSupplier to receive a dependency: 30 * <ul> 31 * <li>To be notified when the object is available, call {@link #onAvailable(Callback)}. 32 * <li>If the object is already available, the Callback will be posted immediately on the handler 33 * for the thread the supplier was created on. 34 * <li>The object held by this supplier will also be returned at the end of {@link 35 * #onAvailable(Callback)}. 36 * <li>The Callback will be called at most once. It's still 37 * recommended to use {@link org.chromium.base.CallbackController} for safety. 38 * </ul> 39 * 40 * @param <T> The type of the wrapped object. 41 */ 42 public interface OneshotSupplier<T> extends Supplier<T> { 43 /** 44 * Add a callback that's called when the object owned by this supplier is available. 45 * If the object is already available, the callback will be called at the end of the 46 * current message loop. 47 * 48 * @param callback The callback to be called. 49 * @return The value for this supplier if already available. Null otherwise. 50 */ 51 @Nullable onAvailable(Callback<T> callback)52 T onAvailable(Callback<T> callback); 53 } 54