1 /* 2 * Copyright (C) 2014 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package dagger.producers; 18 19 import com.google.common.util.concurrent.Futures; 20 import com.google.common.util.concurrent.ListenableFuture; 21 import dagger.internal.Beta; 22 import dagger.producers.internal.CancellableProducer; 23 import dagger.producers.internal.CancellationListener; 24 25 /** Utility methods to create {@link Producer}s. */ 26 @Beta 27 public final class Producers { 28 /** Returns a producer that succeeds with the given value. */ immediateProducer(final T value)29 public static <T> Producer<T> immediateProducer(final T value) { 30 return new ImmediateProducer<>(Futures.immediateFuture(value)); 31 } 32 33 /** Returns a producer that fails with the given exception. */ immediateFailedProducer(final Throwable throwable)34 public static <T> Producer<T> immediateFailedProducer(final Throwable throwable) { 35 return new ImmediateProducer<>(Futures.<T>immediateFailedFuture(throwable)); 36 } 37 38 /** A {@link CancellableProducer} with an immediate result. */ 39 private static final class ImmediateProducer<T> implements CancellableProducer<T> { 40 private final ListenableFuture<T> future; 41 ImmediateProducer(ListenableFuture<T> future)42 ImmediateProducer(ListenableFuture<T> future) { 43 this.future = future; 44 } 45 46 @Override get()47 public ListenableFuture<T> get() { 48 return future; 49 } 50 51 @Override cancel(boolean mayInterruptIfRunning)52 public void cancel(boolean mayInterruptIfRunning) {} 53 54 @Override newDependencyView()55 public Producer<T> newDependencyView() { 56 return this; 57 } 58 59 @Override newEntryPointView(CancellationListener cancellationListener)60 public Producer<T> newEntryPointView(CancellationListener cancellationListener) { 61 return this; 62 } 63 } 64 Producers()65 private Producers() {} 66 } 67