All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dagger.producers.internal.MapOfProducerProducer Maven / Gradle / Ivy

There is a newer version: 2.55
Show newest version
/*
 * Copyright (C) 2016 Google, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dagger.producers.internal;

import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import dagger.internal.Beta;
import dagger.producers.Producer;
import java.util.Map;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newLinkedHashMapWithExpectedSize;

/**
 * A {@link Producer} implementation used to implement {@link Map} bindings. This factory returns an
 * immediate future of {@code Map>} when calling {@link #get}.
 *
 * @author Jesse Beder
 */
@Beta
public final class MapOfProducerProducer extends AbstractProducer>> {
  private static final MapOfProducerProducer EMPTY =
      new MapOfProducerProducer(ImmutableMap.>of());

  private final ImmutableMap> contributingMap;

  /** Returns a new {@link Builder}. */
  public static  Builder builder(int size) {
    return new Builder(size);
  }

  /** Returns a producer of an empty map. */
  @SuppressWarnings("unchecked") // safe contravariant cast
  public static  MapOfProducerProducer empty() {
    return (MapOfProducerProducer) EMPTY;
  }

  private MapOfProducerProducer(ImmutableMap> contributingMap) {
    this.contributingMap = contributingMap;
  }

  @Override
  public ListenableFuture>> compute() {
    return Futures.>>immediateFuture(contributingMap);
  }

  /**
   * A builder to help build the {@link MapOfProducerProducer}
   */
  public static final class Builder {
    private final Map> mapBuilder;

    private Builder(int size) {
      this.mapBuilder = newLinkedHashMapWithExpectedSize(size);
    }

    /** Returns a new {@link MapOfProducerProducer}. */
    public MapOfProducerProducer build() {
      return new MapOfProducerProducer(ImmutableMap.copyOf(mapBuilder));
    }

    /** Associates k with producerOfValue in {@code Builder}. */
    public Builder put(K key, Producer producerOfValue) {
      checkNotNull(key, "key");
      checkNotNull(producerOfValue, "producer of value");
      mapBuilder.put(key, producerOfValue);
      return this;
    }
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy