Last active
March 16, 2019 10:28
-
-
Save mehdok/b88fed1962936c2731d1881c8e218a03 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
package com.sixthsolution.rekab.sharednetwork | |
import io.ktor.client.HttpClient | |
import io.ktor.client.features.ExpectSuccess | |
import io.ktor.client.features.json.JsonFeature | |
import io.ktor.client.features.json.serializer.KotlinxSerializer | |
import io.ktor.client.request.get | |
import io.ktor.http.URLProtocol | |
import kotlinx.coroutines.* | |
import kotlinx.serialization.Serializable | |
import kotlinx.serialization.json.Json | |
import kotlinx.serialization.list | |
import kotlin.coroutines.CoroutineContext | |
internal expect val dispatcher: CoroutineDispatcher | |
class ApiClient: CoroutineScope { | |
private var job: Job = Job() | |
override val coroutineContext: CoroutineContext | |
get() = dispatcher + job | |
private val httpClient = HttpClient { | |
install(JsonFeature) { | |
serializer = KotlinxSerializer().apply { | |
setMapper(Post::class, Post.serializer()) | |
} | |
} | |
install(ExpectSuccess) | |
} | |
fun getPosts(successCallback: (List<Post>) -> Unit, errorCallback: (Exception) -> Unit) { | |
launch { | |
try { | |
val result: String = httpClient.get { | |
url { | |
protocol = URLProtocol.HTTPS | |
port = 443 | |
host = "jsonplaceholder.typicode.com" | |
encodedPath = "/posts" | |
} | |
} | |
val repos = Json.parse(Post.serializer().list, result) | |
successCallback(repos) | |
} catch (ex: Exception) { | |
errorCallback(ex) | |
} | |
} | |
} | |
fun dispose() { | |
job.cancel() | |
} | |
} | |
@Serializable | |
data class Post(val userId: Int, val id: Int, val title: String, val body: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment