gpt4 book ai didi

java - 模块必须设置 Dagger 2

转载 作者:行者123 更新时间:2023-12-01 19:53:17 24 4
gpt4 key购买 nike

我正在尝试使用 dagger 2 和 kotlin 创建依赖项。我在运行时收到此错误

Caused by: java.lang.IllegalStateException: pk.telenorbank.easypaisa.di.modules.RetrofitApiModule must be set at pk.telenorbank.easypaisa.di.DaggerAppComponent$Builder.build(DaggerAppComponent.java:54) at pk.telenorbank.easypaisa.EasypaisaApp.onCreate(EasypaisaApp.kt:22) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1015) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4834) at android.app.ActivityThread.access$1600(ActivityThread.java:168)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:150)  at android.app.ActivityThread.main(ActivityThread.java:5659)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712) 

这是依赖图。

@Module(includes = arrayOf(NetworkModule::class))
class RetrofitApiModule(val retrofitMvpApi: RetrofitMvpApi) {
@Provides
@Singleton
fun provideMvpApi(): RetrofitMvpApi {
return retrofitMvpApi
}
}

这里是 RetorfitMvpApi

@Singleton
class RetrofitMvpApi @Inject constructor(retrofit: Retrofit) : MvpApi {

var retrofitService: RetrofitService

init {
retrofitService = retrofit.create(RetrofitService::class.java)
}

override fun login(source: String) =
retrofitService.getPosts(source, Constants.API_KEY)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map { rs -> rs }
.doOnError { t -> t.printStackTrace() }


interface RetrofitService {
@POST
fun getPosts(@Query("sources") source: String,
@Query("apiKey") key: String): Observable<WSResponse>
}
}

这是组件。

@Singleton
@Component(modules = arrayOf(AppModule::class, RetrofitApiModule::class))
interface AppComponent {

fun loginComponent(loginModule: LoginModule) : LoginComponent
}

我在这里做错了什么?我正在使用dagger 2.15

最佳答案

如果Module具有默认构造函数,

Dagger将自动为依赖图创建Module。如果您使用自定义构造函数,则在构建图表时必须提供模块

对于java代码:

@Module
public class ContextModule {

private final Context context;

public ContextModule(Context context) {
this.context = context;
}

@Provides
@GithubApplicationScope
@ApplicationContext
public Context provideContext(){
return context.getApplicationContext();
}

}

构建图表:

    githubApplicationComponent = DaggerGithubApplicationComponent.builder()
.contextModule(new ContextModule(this))
// not needed as Dagger automatically generate module class with no arguments
//.networkModule(new NetworkModule())
.build();

关于java - 模块必须设置 Dagger 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50514896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com