Retrofit
Usage
- Add JitPack to your project build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
- Add the dependency in the application build.gradle
dependencies {
implementation "com.github.FunkyMuse.KAHelpers:retrofit:$utilsVersion"
}
- Simple usage
private val retrofit by lazy {
RetrofitClient.moshiInstanceCoroutines(application, TestApi.url, enableDebuggingInterceptor = BuildConfig.DEBUG).create<TestApi>()
}
- Custom usage
Your retrofit
private val retrofit by lazy {
RetrofitClient.customInstance(application, TestApi.API, false, builderCallback = {
addCallAdapterFactory(ApiResultAdapterFactory())
addConverterFactory(MoshiConverterFactory.create())
this
}).create<TestApi>()
}
Your API
@GET("posts")
suspend fun getPostsAdapter(): ApiResult<List<TestModel>>
Your view model
private val postsData: MutableStateFlow<ApiResult<List<TestModel>>> = MutableStateFlow(ApiResult.EmptyData)
val posts: MutableStateFlow<ApiResult<List<TestModel>>> = postsData
fun getposts() {
postsData.value = ApiResult.Loading
viewModelScope.launch(ioDispatcher + SupervisorJob()) {
delay(3000) //simulating network delay
postsData.value = retrofit.getPostsAdapter()
}
}