Предоставить контекст приложения с помощью кинжала 2 - PullRequest
0 голосов
/ 20 декабря 2018

Всем доброго времени суток,

Я хотел бы предоставить контекст приложения для моего класса AppModule.

Я бы хотел, чтобы PrefsHelper предоставлялся через приложение, как я это делаю с моим ApiService.class.

Код для моего AppModule:

@Module
@Suppress("unused")
object AppModule {

    @Provides
    @Reusable
    @JvmStatic
    internal fun provideApiService(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }

    /**
     * Provides the Retrofit object.
     * @return the Retrofit object
     */
    @Provides
    @Reusable
    @JvmStatic
    internal fun provideRetrofitInterface(): Retrofit {
    val interceptor: HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
        this.level = HttpLoggingInterceptor.Level.BODY
    }
    val client: OkHttpClient = OkHttpClient.Builder().apply { this.addInterceptor(interceptor) }.build()
    return Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .client(client)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
            .addConverterFactory(GsonConverterFactory.create())
            .build()
}

То, как я видел это раньше (в Java), - это создание конструктора и передача таким образом контекста приложения.Kotlin не допускает этого с object

. Как мне обеспечить контекст в этом классе, позволяющий мне предоставить PrefsHelper?

Ответы [ 2 ]

0 голосов
/ 20 декабря 2018

Вы также можете использовать аннотацию BindsInstance в вашем AppComponent.

Итак, ваш AppComponent будет выглядеть примерно так:

@Singleton
@Component(modules = YOUR_MODULES)
interface AppComponent {

//Whatever injections you have

   @Component.Builder
   interface Builder {

      fun build(): AppComponent

      @BindsInstance 
      fun application(Application application): Builder      
  }
}

Затем вы просто добавляете новые методы к вашему AppComponent созданию в вашем Application class.

DaggerAppComponent.builder().application(this).build()
0 голосов
/ 20 декабря 2018

Измените AppModule на что-то вроде этого:

@Module
class AppModule(private val application: Application) {

    @Singleton
    @Provides
    internal fun provideApplication(): Application = application

    @Singleton
    @Provides
    internal fun providePrefs(application: Application): YourPref {
        return YourPref(application)
    }

}
...