Skip to content

Instantly share code, notes, and snippets.

@JanStoltman
Last active September 21, 2020 07:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JanStoltman/9c802d06c469de46f2d76ad6bfbe5a28 to your computer and use it in GitHub Desktop.
Save JanStoltman/9c802d06c469de46f2d76ad6bfbe5a28 to your computer and use it in GitHub Desktop.
`backgroundSuspend` method is the same as in DroidconKotlin example. All classes are brought together using Kodein dependency injection.
class ApiClientServiceImpl(
client: HttpClient, parser: JsonParser
) : BaseApiClientService(client, parser) {
override suspend fun getCategories() =
requestCatching(Category.serializer().list) {
get()
apiUrl("/api/product/live/category/list")
accessHeaders()
}
}
actual object AppHttpClient {
actual val client = HttpClient(Ios)
}
abstract class BaseApiClientService(
protected val client: HttpClient,
private val parser: JsonParser
) : ApiClientService {
protected suspend fun <T> requestCatching(kserializer: KSerializer<T>, block: HttpRequestBuilder.() -> Unit) =
requestCatching(block).mapCatching {
it.serialize(kserializer)
}
protected suspend fun requestCatching(block: HttpRequestBuilder.() -> Unit) =
runCatching {
client.request<String> {
block()
}
}
@Throws
private suspend fun <T> String.serialize(kserializer: KSerializer<T>) =
parser.parse(this, kserializer).getOrThrow()
}
class JsonParser {
suspend fun <T> parse(json: String, deserializer: DeserializationStrategy<T>) =
runCatching {
backgroundSuspend {
Json.nonstrict.parse(deserializer, json)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment