如何在其构造函数中匕首注入需要接口对象的类

时间:2017-07-07 08:07:24

标签: java android dependency-injection dagger-2

我有一个简单的Repository类FoodDataRepository,在构造函数中只需要一个Interface对象,我需要在FoodDataRepository类中注入Presenter的实例。到目前为止,我已经在下面进行了此操作,但我没有遇到任何崩溃,但FoodDataRepositor dosn中注入FoodPresenter似乎无法正常工作或做任何事情。

FoodDataRepository.class

public class FoodDatRepository {

public FoodDatRepositoryListener listener;

public FoodDatRepository(final FoodDatRepositoryListener listener) {
    this.listener = listener;

    BackendService backendService = BackendServiceFactory.makeBackendService();
    backendService.getFoodData().enqueue(new Callback<Data>() {
        @Override
        public void onResponse(Call<Data> call, Response<Data> response) {
            if (response.isSuccessful() && listener != null) {
                listener.onSetData(response.body());
            }
        }

        @Override
        public void onFailure(Call<Data> call, Throwable t) {

        }
    });
  }

}

FoodPresenter.class:

public class FoodPresenter implements FoodDatRepositoryListener {


@Inject
FoodDataRepository repository;

public FoodPresenter() {

}


@Override
public void onSetData(Data data) {


   }
}

FoodDataRepositoryModule

@Module
public class FoodDataRepositoryModule {

@Provides
FoodDataRepositoryListener provideListener() {
    return new FoodDataRepositoryListener() {
        @Override
        public void onSetData(Data data) {

        }
    };
}

@Provides
FoodDataRepository provideRepository(FoodDataRepositoryListener listener) {
    return new FoodDataRepository(listener);
}

}  

注射器

@Singleton
@Component(modules = {
    FoodDataRepositoryModule.class
})


public interface Injector {
void inject(FoodPresenter foodPresenter);
}

0 个答案:

没有答案