1

How would I inject an instance of GetTodoRepository to MainViewModel when GetTodoRepository requires a listener in its constructor? Obviously the easist solution would be to have setListener() instead of setting it in the constructor or using RxJava, but I would still like to know how it would be done otherwise.

MainViewModel

public class MainViewModel extends ViewModel implements GetTodoRepository.ResultListener {

    private GetTodoRepository getTodoRepository;

    public MainViewModel() {
    getTodoRepository = new GetTodoRepository(this);
}

GetTodoRepository

public class GetTodoRepository {

    private ResultListener listener;

    public GetTodoRepository(@NonNull ResultListener listener) {
    this.listener = listener;
    }

    public interface ResultListener {
    void onGetTodoSuccess(String data);
    void onGetTodoFailed(String msg);
    }
}

Dagger Component

@Component(modules = AppModule.class)
public interface AppComponent {
void inject(MainViewModel viewModel);
void inject(GetTodoRepository getTodoRepository);

}
  • A lot of this depends on what you actually want to have happen here. Is there a single GetTodoRepository? Do you want all instances of GetTodoRepository to use the same listener? Or do you want to create different repositories with listener parameters (in which case why are you injecting vs new, unless there's a mix of injected and non-injected parameters, in which case look at assisted injection)? – Gabe Sechan Jan 26 '20 at 20:27
  • @GabeSechan `GetTodoRepository` just makes a `GET` call with Retrofit and posts its result to the `MainViewModel` with the `ResultListener`. –  Jan 26 '20 at 20:32
  • So you probably just want to have it take a listener at creation time which will be unique per call- so why inject at all? Just have it use new. Unless you have a mix of injected and non injected parameters, in which case use assisted injection. – Gabe Sechan Jan 26 '20 at 20:35

0 Answers0