• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.NonNull;
8 import androidx.annotation.Nullable;
9 
10 import org.chromium.base.Callback;
11 import org.chromium.base.Promise;
12 import org.chromium.base.ThreadUtils;
13 
14 /**
15  * Concrete implementation of {@link OneshotSupplier} to be used by classes owning a
16  * OneshotSupplier and providing it as a dependency to others.
17  *
18  * <p>Instances of this class must only be accessed from the thread they were created on.
19  *
20  * To use:
21  * <ol>
22  *    <li>Create a new {@code OneshotSupplierImpl<T>} to pass as a dependency.
23  *    <li>Call {@link #set(Object)} when the object becomes available. {@link #set(Object)} may only
24  * be called once.
25  * </ol>
26  *
27  * @param <T> The type of the wrapped object.
28  */
29 public class OneshotSupplierImpl<T> implements OneshotSupplier<T> {
30     private final Promise<T> mPromise = new Promise<>();
31     private final ThreadUtils.ThreadChecker mThreadChecker = new ThreadUtils.ThreadChecker();
32 
33     @Override
onAvailable(Callback<T> callback)34     public T onAvailable(Callback<T> callback) {
35         mThreadChecker.assertOnValidThread();
36         mPromise.then(callback);
37         return get();
38     }
39 
40     @Override
get()41     public @Nullable T get() {
42         mThreadChecker.assertOnValidThread();
43         return mPromise.isFulfilled() ? mPromise.getResult() : null;
44     }
45 
46     /**
47      * Set the object supplied by this supplier. This will post notifications to registered
48      * callbacks that the dependency is available. If set() has already been called, this method
49      * will assert.
50      *
51      * @param object The object to supply.
52      */
set(@onNull T object)53     public void set(@NonNull T object) {
54         mThreadChecker.assertOnValidThread();
55         assert !mPromise.isFulfilled();
56         assert object != null;
57         mPromise.fulfill(object);
58     }
59 }
60