CodexBloom - Programming Q&A Platform

Struggling with Retrofit and Coroutine Integration in a Migration to Hilt for Dependency Injection

👀 Views: 48 💬 Answers: 1 📅 Created: 2025-10-05
android hilt retrofit coroutines kotlin

Part of a larger system involves migrating an existing app to use Hilt for dependency injection, and I am tasked with integrating Retrofit for network calls using Kotlin Coroutines. I've set up Hilt correctly, verified that the dependencies are injected, but when I attempt to make a network call within a ViewModel, it seems to hang indefinitely. Here’s what I’ve done so far: 1. Defined my Retrofit API interface: ```kotlin interface ApiService { @GET("data") suspend fun fetchData(): Response<List<DataModel>> } ``` 2. Created a Hilt module to provide the Retrofit instance: ```kotlin @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideRetrofit(): Retrofit { return Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build() } @Provides @Singleton fun provideApiService(retrofit: Retrofit): ApiService { return retrofit.create(ApiService::class.java) } } ``` 3. Injected the ApiService into my ViewModel: ```kotlin @HiltViewModel class MyViewModel @Inject constructor(private val apiService: ApiService) : ViewModel() { fun loadData() = viewModelScope.launch { val response = apiService.fetchData() // Handle response here } } ``` Despite everything appearing correct, the coroutine within `loadData()` does not finish executing. I’ve tried using `withContext(Dispatchers.IO)` inside the coroutine, but it didn't help. Here’s the error I see in my logs: ``` java.lang.IllegalStateException: Expected to be called from a coroutine or another suspend function ``` It’s puzzling because I thought using `viewModelScope` would suffice. Could it be related to how Hilt manages the lifecycle or how the Retrofit call is structured? Any insights into how to troubleshoot this would be greatly appreciated! For context: I'm using Kotlin on Linux. Any suggestions would be helpful.