在有關 Hilt 的檔案中,它顯示了將視圖模型注入活動的示例:
@HiltViewModel
class ExampleViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
private val repository: ExampleRepository
) : ViewModel() {
...
}
@AndroidEntryPoint
class ExampleActivity : AppCompatActivity() {
private val exampleViewModel: ExampleViewModel by viewModels()
...
}
但是如果 ExampleRepository 本身有一個需要引數的建構式呢?活動中的代碼有何不同?你如何告訴 Hilt 將哪些引數傳遞給 Repository?
uj5u.com熱心網友回復:
有多種方法,但我會提到一種我用于來自自定義型別的引數的方法,例如改造 api 服務或 OKHttp,您需要像下面那樣提供它
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
fun provideOkHttpClient(
@ApplicationContext context: Context,
networkManager: NetworkManager,
authenticator: AuthInterceptor,
preferenceHelper: PreferenceHelper
): OkHttpClient {
val httpLogging = HttpLoggingInterceptor()
httpLogging.level = HttpLoggingInterceptor.Level.BODY
val httpClient = OkHttpClient.Builder()
.addInterceptor(authenticator)
.connectTimeout(5, TimeUnit.MINUTES)
.callTimeout(5, TimeUnit.MINUTES)
.readTimeout(2, TimeUnit.MINUTES)
.writeTimeout(2, TimeUnit.MINUTES)
if (BuildConfig.BUILD_TYPE == Constants.STAGING_RELEASE)
httpClient.addInterceptor(httpLogging)
httpClient.addInterceptor(ChuckInterceptor(context))
val httpCacheDirectory = File(context.cacheDir, "responses")
val cacheSize: Long = 10 * 1024 * 1024
val cache = Cache(httpCacheDirectory, cacheSize)
httpClient.cache(cache)
return httpClient.build()
}
}
in this way when a parameter of type OkHttpClient is needed, this function will return it
uj5u.com熱心網友回復:
你怎么告訴的Hilt?帶注釋。Jake Wharton有一篇關于依賴注入如何作業的非常好的演講Dagger2(Hilt基于它,所以想法是一樣的)。
Dagger2/Hilt/DI 的大部分內容是Service Locator。Hilt是編譯時的事情,因此它會使用這些注釋遍歷所有檔案,并注意在何處提供什么以及需要什么,并生成“在后臺”執行所有這些邏輯的檔案。
即使在您的示例中:
@HiltViewModel
class ExampleViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
private val repository: ExampleRepository
) : ViewModel() {
...
}
你告訴Hilt那ExampleViewModel是一個@HiltViewModel. 你還說你想Hilt為你創建它 - with @Inject- 你說你希望它有兩個引數savedStateHandle和repository。現在Hilt將嘗試在您的檔案中找到是否存在ExampleRepositorywith@Inject或某個模塊@Provides是否明確。
class ExampleRepository @Inject constructor() {
...
}
或者
@Module
@InstallIn(SingletonComponent::class)
object StorageModule {
@Provides
fun provideExampleRepository(): ExampleRepository = ExampleRepository()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524117.html
標籤:安卓匕首
