Retrofit suspend function throws generic error

Viewed 152

Im trying to setup Retrofit2 with suspend functions but I am having unexpected error while in offline mode (all good in online mode).

ApiService:

interface ApiService {
    @GET("v2/153")
    suspend fun fetchData(): Response<DataModel>
}

Retrofit Client:

fun provideDefaultOkhttpClient(context: Context): OkHttpClient {
    val cacheSize = (5 * 1024 * 1024).toLong()
    return OkHttpClient.Builder()
        .cache(Cache(context.cacheDir, cacheSize))
        .build()
}

fun provideRetrofit(client: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .client(client)
        .baseUrl(BASE_URL)
        .addConverterFactory(MoshiConverterFactory.create())
        .build()
}

fun provideApiService(retrofit: Retrofit): ApiService =
    retrofit.create(ApiService::class.java)

DataRepository:

class DataRepository(private val api: ApiService) {

    suspend fun getData(): List<DataModel>? {
        val myData = api.fetchData()

        return if (myData.isSuccessful) {
            myData.body()
        } else {
            null
        }
    }
}

While debugging the app I see the DataRepository->api.fetchData() being called, and from there it hangs and I get the following error:

2019-06-28 10:35:46.136 10876-10876/com.myapp.name.debug E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.myapp.name.debug, PID: 10876

What am I missing? Or am I just wrongly using suspend function to retrieve data?

0 Answers
Related