Last active
September 21, 2020 07:53
-
-
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.
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 ApiClientServiceImpl( | |
client: HttpClient, parser: JsonParser | |
) : BaseApiClientService(client, parser) { | |
override suspend fun getCategories() = | |
requestCatching(Category.serializer().list) { | |
get() | |
apiUrl("/api/product/live/category/list") | |
accessHeaders() | |
} | |
} |
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
actual object AppHttpClient { | |
actual val client = HttpClient(Ios) | |
} |
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
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() | |
} |
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 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