Last active
March 23, 2023 13:15
-
-
Save javaherisaber/a60dde22af513f0acf9c18e64f3430ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RemoteDataSource(private val context: Context) { | |
fun api(): Api { | |
val mockFitInterceptor = provideMockFitInterceptor(context) | |
val okHttpClient = provideOkHttpClient(mockFitInterceptor) | |
val retrofit = provideRetrofit(okHttpClient) | |
return retrofit.create(Api::class.java) | |
} | |
private fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder() | |
.baseUrl(BASE_URL) | |
.addConverterFactory(GsonConverterFactory.create()) | |
.client(okHttpClient) | |
.build() | |
private fun provideMockFitInterceptor(context: Context) = MockFitInterceptor( | |
bodyFactory = { input -> context.resources.assets.open(input) }, // read asset file | |
logger = { tag, message -> Log.d(tag, message) }, // pass logger to log events in logcat | |
baseUrl = BASE_URL, // base url of your api | |
requestPathToMockPathRule = REQUEST_TO_JSON, // autogenerated constant, just press build button | |
mockFilesPath = MOCK_FILES_PATH, // path to json files | |
mockFitEnable = true, // master setting to enable or disable mocking | |
apiEnableMock = true, // enable or disable mock when there are includes and excludes configs | |
apiIncludeIntoMock = arrayOf(), // include endpoint if `apiEnableMock` is false | |
apiExcludeFromMock = arrayOf(), // exclude endpoint if `apiEnableMock` is true | |
apiResponseLatency = 500L // latency of retrieving data | |
) | |
private fun provideOkHttpClient(mockFitInterceptor: MockFitInterceptor) = OkHttpClient.Builder() | |
.addInterceptor(mockFitInterceptor) | |
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) | |
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) | |
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) | |
.build() | |
companion object { | |
private const val BASE_URL = "https://picsum.photos/v2/" | |
private const val MOCK_FILES_PATH = "mock_json" // located at assets/mock_json/ | |
private const val CONNECT_TIMEOUT = 20L | |
private const val WRITE_TIMEOUT = 20L | |
private const val READ_TIMEOUT = 30L | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment