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

com.bumptech.glide.load.data.DataRewinderRegistry Maven / Gradle / Ivy

Go to download

A fast and efficient image loading library for Android focused on smooth scrolling.

There is a newer version: 5.0.0-rc01
Show newest version
package com.bumptech.glide.load.data;

import androidx.annotation.NonNull;
import com.bumptech.glide.util.Preconditions;
import java.util.HashMap;
import java.util.Map;

/**
 * Stores a mapping of data class to {@link com.bumptech.glide.load.data.DataRewinder.Factory} and
 * allows registration of new types and factories.
 */
public class DataRewinderRegistry {
  private final Map, DataRewinder.Factory> rewinders = new HashMap<>();
  private static final DataRewinder.Factory DEFAULT_FACTORY =
      new DataRewinder.Factory() {
        @NonNull
        @Override
        public DataRewinder build(@NonNull Object data) {
          return new DefaultRewinder(data);
        }

        @NonNull
        @Override
        public Class getDataClass() {
          throw new UnsupportedOperationException("Not implemented");
        }
      };

  public synchronized void register(@NonNull DataRewinder.Factory factory) {
    rewinders.put(factory.getDataClass(), factory);
  }

  @NonNull
  @SuppressWarnings("unchecked")
  public synchronized  DataRewinder build(@NonNull T data) {
    Preconditions.checkNotNull(data);
    DataRewinder.Factory result = (DataRewinder.Factory) rewinders.get(data.getClass());
    if (result == null) {
      for (DataRewinder.Factory registeredFactory : rewinders.values()) {
        if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {
          result = (DataRewinder.Factory) registeredFactory;
          break;
        }
      }
    }

    if (result == null) {
      result = (DataRewinder.Factory) DEFAULT_FACTORY;
    }
    return result.build(data);
  }

  private static final class DefaultRewinder implements DataRewinder {
    private final Object data;

    DefaultRewinder(@NonNull Object data) {
      this.data = data;
    }

    @NonNull
    @Override
    public Object rewindAndGet() {
      return data;
    }

    @Override
    public void cleanup() {
      // Do nothing.
    }
  }
}