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; 6 7 import androidx.annotation.NonNull; 8 9 /** 10 * A simple single-argument callback to handle the result of a computation that must be called 11 * exactly once. 12 * 13 * @param <T> The type of the computation's result. 14 */ 15 public class RequiredCallback<T> implements Callback<T> { 16 // Enforces (under test) that this callback is invoked before it is GC'd. 17 private final LifetimeAssert mLifetimeAssert = LifetimeAssert.create(this); 18 private Callback<T> mCallback; 19 RequiredCallback(@onNull Callback<T> callback)20 public RequiredCallback(@NonNull Callback<T> callback) { 21 mCallback = callback; 22 } 23 24 @Override onResult(T result)25 public void onResult(T result) { 26 assert mCallback != null : "Callback was already called."; 27 mCallback.onResult(result); 28 LifetimeAssert.setSafeToGc(mLifetimeAssert, true); 29 mCallback = null; 30 } 31 } 32