Skip to content

Instantly share code, notes, and snippets.

@alaershov
Created January 23, 2020 13:51
Show Gist options
  • Save alaershov/6446c9463a748a164cb557e326348d9e to your computer and use it in GitHub Desktop.
Save alaershov/6446c9463a748a164cb557e326348d9e to your computer and use it in GitHub Desktop.
Toothpick bind samples
// Допустим, у вас есть интерфейс ProjectRepository, его реализация ProjectServerRepository.
// И вы хотите забиндить интерфейс к реализации.
public class ProjectServerRepository implements ProjectRepository {
@Inject
public ProjectServerRepository(Context context) {...}
}
public class MyModule extends Module {
public MyModule() {
// Вариант первый: указываем, экземпляр какого класса создать с помощью Inject-конструктора.
bind(ProjectRepository.class).to(ProjectServerRepository.class);
// Вариант второй: создаём инстанс вручную.
bind(ProjectRepository.class).toInstance(new ProjectServerRepository(...));
// Вариант третий: ProjectServerRepository нужны какие-то ещё зависимости из графа, и мы почему-то
// не можем сделать @Inject-конструктор. Нужен Provider.
bind(ProjectRepository.class).toProvider(ProjectRepositoryProvider.class);
}
}
public class ProjectRepositoryProvider implements Provider<ProjectRepository> {
private final Context context;
// Toothpick найдет провайдер по классу, и создаст его с помощью того Inject-конструктора, передав туда Context.
// Потом с помощью этого провайдер создаст ProjectServerRepository.
// Да, это такой длинный аналог @Provide-метода из Dagger, поэтому провайдеры обычно нужны в крайнем случае.
@Inject
public ProjectRepositoryProvider(Context context) {
this.context = context;
}
@Override
public ProjectRepository get() {
return new ProjectServerRepository(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment