<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Suat Zengin on Medium]]></title>
        <description><![CDATA[Stories by Suat Zengin on Medium]]></description>
        <link>https://medium.com/@suatzengin?source=rss-86a78b9ef5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*debWHXQS84kQdGd8UhHAXA.jpeg</url>
            <title>Stories by Suat Zengin on Medium</title>
            <link>https://medium.com/@suatzengin?source=rss-86a78b9ef5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:27:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@suatzengin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android WebSocket with Ktor — Server/Client]]></title>
            <link>https://medium.com/@suatzengin/android-websocket-with-ktor-server-client-d28b37cd38a4?source=rss-86a78b9ef5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d28b37cd38a4</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Suat Zengin]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 19:38:49 GMT</pubDate>
            <atom:updated>2024-09-17T19:38:49.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android WebSocket with Ktor — Server/Client</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNjOyTJv3Z3SnMORUn8P2Q.jpeg" /></figure><h3>What is WebSocket?</h3><p>WebSocket is a bidirectional communication protocol that provides a permanent connection between client and server that remains active for a long time.<br>It enables continuous, instant, real-time data exchange between the client and the server. Unlike HTTP, it doesn’t require sending and waiting for a request.<br>A WebSocket connection remains open until either the client or the server closes it.<br>WebSocket was born from the limitations of HTTP. Using HTTP for instantaneous data exchanges would result in a lot of traffic and therefore cost. WebSocket also works over HTTP with a TCP/IP socket connection. It uses HTTP but ensures that the connection with TCP remains active and maintained.</p><p>WebSocket uses the following endpoints:</p><ul><li><strong>“ws://”</strong></li><li><strong>“wss://”</strong></li></ul><h3>Client-Server Connection</h3><p>First, Client sends an HTTP GET request to the server to create the WebSocket connection with some information in the Header:</p><ul><li><strong>Upgrade</strong>: “<strong>websocket</strong>” : Client wants to upgrade the current HTTP protocol to WebSocket.</li><li><strong>Connection</strong>: “<strong>Upgrade</strong>” : Client indicates that the connection needs to be upgraded.</li></ul><p>The server receives this request and returns an HTTP 101 Switching Protocols status code to the client with same two information in the Header:</p><ul><li><strong>Upgrade</strong>: “<strong>websocket</strong>”: The server accepts to switch to the WebSocket protocol.</li><li><strong>Connection</strong>: “<strong>Upgrade</strong>”: Connection upgraded.</li></ul><p>Once this flow, called Handshake, is complete, the WebSocket connection is established.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNLrqQUnGi9h3DZL-lGarA.png" /><figcaption>WebSocket connection flow between client and server</figcaption></figure><h3>Let’s code 👨🏻‍💻</h3><p>We’ll make a WebSocket sample using Ktor Server. First, go to the <a href="https://start.ktor.io/?_gl=1*11nnb1d*_gcl_au*MTczNTg3MzU4MC4xNzI1MDQ5NjU4*_ga*NDU5MjM0MTU3LjE3MDE4NTUyNTU.*_ga_9J976DJZ68*MTcyNjA4MTMxNS41Ni4xLjE3MjYwODE0NzguMTUuMC4w">Ktor Project Generator</a> page, select the dependencies and click the Download button. Dependencies:</p><ul><li>Routing</li><li>WebSockets</li><li>Serialization and Content Negotiation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6wdwx1_HzI8Vqn6P9WUZNw.png" /><figcaption>Ktor project generator</figcaption></figure><p>After downloading and opening the project, we can install the WebSocket plugin in <strong><em>../plugins/Socket.kt</em></strong> and change its configuration.</p><pre>fun Application.configureSockets() {<br>    install(WebSockets) {<br>        pingPeriod = Duration.ofSeconds(15)<br>        timeout = Duration.ofSeconds(15)<br>        maxFrameSize = Long.MAX_VALUE<br>        masking = false<br>    }<br>}</pre><p>Once you have installed and configured the WebSockets plugin, we can define an endpoint to handle a WebSocket session. To define a WebSocket endpoint on a server, call the webSocket function inside the <a href="https://ktor.io/docs/server-routing.html#define_route">routing</a> block:</p><pre>fun Application.webSocketRouting() {<br>    routing {<br>        webSocket(&quot;/btc&quot;) {<br>            while (true) {<br>                delay(1000)<br><br>                send(&quot;${Random.nextDouble(0.005, 0.999)}&quot;) //WebSocketSession.send(/**/)<br>            }<br>        }<br>    }<br>}</pre><ul><li>send: Use to send text content to the client.</li></ul><p>Additionally, we have a outgoing.send (SendChannel.send) function to send data to the client. The difference is:</p><ul><li>WebSocketSession.send is a high-level function that abstracts the process of sending data. We can use it with String, ByteArray or Frame parameters, and it automatically converts them to the appropriate WebSocket frames.</li><li>outgoing.send is a lower-level function that requires working directly with Frame objects.</li><li>send() is used for convenience and simplicity, while outgoing.send() is useful when you need finer control over the Frame, such as handling binary Frames or fragmented messages.</li></ul><p>We define an endpoint as ‘<strong>/btc’</strong> and send a random value text to the client every 1000 ms. That’s it. Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*elkrEaJNF1DK5T6m2LXMdA.gif" /></figure><p>Okay, we sent the data to the client, but what about receiving data from the client? Before coding, let’s look at these two concepts:</p><ul><li>incoming : Use to access channels for receiving WebSocket Frames. <br><em>type</em> -&gt; ReceiveChannel&lt;Frame&gt;</li><li>outgoing : Use to access channels for sending WebSocket Frames. <br><em>type</em> -&gt; SendChannel&lt;Frame&gt;</li><li>close : Use to send a close frame with the specified reason</li></ul><pre>webSocket(&quot;/ws&quot;) {<br>    incoming.consumeEach { frame -&gt;<br>        if(frame is Frame.Text) {<br>            val text = frame.readText() // received from the client<br><br>            send(Frame.Text(&quot;Sent to client again: $text&quot;))<br><br>            if(text == &quot;bye&quot;) {<br>                close(CloseReason(CloseReason.Codes.NORMAL, message = &quot;Bye&quot;))<br>            }<br>        }<br>    }<br>}</pre><ul><li>consumeEach is a suspending function that iterates over and processes each item in a ReceiveChannel, consuming the elements one by one. It’s commonly used to handle incoming WebSocket frames, ensuring that each Frame is processed asynchronously until the channel is closed.</li><li>Using frame.readText() function, we can read Text Frame’s content.</li><li>Using frame.readBytes() function, we can read Binary Frame’s content.</li></ul><p>If you want to send JSON data instead of plain text, we will need to use Serialization. For this, we will first add to the WebSocket configuration. To add JSON serializer, we need to create <strong>KotlinxWebsocketSerializationConverter</strong> instance by giving <strong>Json</strong> parameter and assign it to <strong>contentConverter</strong>.</p><pre>fun Application.configureSockets() {<br>    install(WebSockets) {<br>        contentConverter = KotlinxWebsocketSerializationConverter(Json) //Add this for serialization<br>        pingPeriod = Duration.ofSeconds(15)<br>        timeout = Duration.ofSeconds(15)<br>        maxFrameSize = Long.MAX_VALUE<br>        masking = false<br>    }<br>}</pre><p>Now, we need to create a data class for our JSON data model and add <strong>@Serializable</strong> annotation.</p><pre>@Serializable<br>data class Coin(<br>    val name: String,<br>    val symbol: String,<br>    val price: Double,<br>)<br><br>val Btc = Coin(<br>    name = &quot;Bitcoin&quot;,<br>    symbol = &quot;BTC&quot;,<br>    price = 68000.0,<br>)<br><br>val Eth = Coin(<br>    name = &quot;Ethereum&quot;,<br>    symbol = &quot;ETH&quot;,<br>    price = 2300.0,<br>)<br><br>val coinList: List&lt;Coin&gt; = listOf(Btc, Eth)<br></pre><p>After creating the list to send, we can define an endpoint to handle a WebSocket session.</p><pre>// Routing.kt<br>fun Application.webSocketRouting() {<br>    routing {<br>        webSocket(&quot;/cryptos&quot;) {<br>            val receivedCrypto: Coin = receiveDeserialized&lt;Coin&gt;() // receive from client<br>            sendSerialized(receivedCrypto) // send received coin<br>            delay(1000)<br>            coinList.forEach {<br>                sendSerialized(it) // send coin list items to clients<br>                delay(1000)<br>            }<br>        }<br>    }<br>}</pre><ul><li>receiveDeserialized&lt;Coin&gt;() : Deserialize the coin data that received as JSON from the client.</li><li>sendSerialized(...) : Serialize the coin data (receivedCrypto) as JSON and send to the client again.</li><li>Also, in the coinList.forEach block, send all coins to the client with a delay.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93XAz1h7817ehFJLjmd_Ow.gif" /></figure><h3>Ktor Client</h3><p>After the server installation, let’s see our data on our application screen by adding the dependencies on the client side.</p><p>Let’s start by adding dependencies:</p><pre># libs.versions.toml<br><br>[versions]<br>ktorVersion = &quot;2.3.11&quot;<br>kotlin = &quot;1.9.0&quot;<br><br>[libraries]<br>ktor-client-okhttp = { module = &quot;io.ktor:ktor-client-okhttp&quot;, version.ref = &quot;ktorVersion&quot; }<br>ktor-client-websocket = { module = &quot;io.ktor:ktor-client-websockets&quot;, version.ref = &quot;ktorVersion&quot; }<br>ktor-client-content-negotiation = { module = &quot;io.ktor:ktor-client-content-negotiation&quot;, version.ref = &quot;ktorVersion&quot; }<br>ktor-client-core = { module = &quot;io.ktor:ktor-client-core&quot;, version.ref = &quot;ktorVersion&quot; }<br>ktor-serialization-kotlinx-json = { module = &quot;io.ktor:ktor-serialization-kotlinx-json&quot;, version.ref = &quot;ktorVersion&quot; }<br><br>[plugins]<br>kotlin-serialization = { id = &quot;org.jetbrains.kotlin.plugin.serialization&quot;, version.ref = &quot;kotlin&quot; </pre><pre>//build.gradle.kts (project)<br><br>plugins {<br>    //....<br>    alias(libs.plugins.kotlin.serialization) apply false<br>}</pre><pre>//build.gradle.kts (app)<br><br>plugins {<br>    //....<br>    alias(libs.plugins.kotlin.serialization)<br>}<br><br>dependencies {<br>    //....<br>    <br>    implementation(libs.ktor.client.core)<br>    implementation (libs.ktor.client.okhttp)<br>    implementation (libs.ktor.client.websocket)<br>    implementation (libs.ktor.client.content.negotiation)<br>    implementation (libs.ktor.serialization.kotlinx.json)<br><br>    //....<br>}</pre><p>After adding the dependencies, we can now move on to creating our HttpClient object:</p><pre>object KtorClient {<br>    val httpClient: HttpClient = HttpClient(OkHttp) {<br>        install(WebSockets) {<br>            pingInterval = 20_000<br>            contentConverter = KotlinxWebsocketSerializationConverter(Json)<br>        }<br><br>        install(ContentNegotiation) {<br>            json(<br>                Json {<br>                    prettyPrint = true<br>                    isLenient = true<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>After setting our HttpClient settings, we can start communicating with the Server. Let’s create a Data Source class and manage the WebSocket session.</p><pre>class WebSocketDataSource {<br>    private var socket: DefaultClientWebSocketSession? = null<br><br>    suspend fun connect(<br>        onMessage: (String) -&gt; Unit,<br>        onClose: () -&gt; Unit,<br>        onError: (errorMessage: String) -&gt; Unit<br>    ) {<br>        runCatching {<br>            socket = KtorClient.httpClient.webSocketSession {<br>                url(https://medium.com/&quot;ws://localhost:8080/btc&quot;)<br>            }<br><br>            while (true) {<br>                val frame = socket?.incoming?.receive() as? Frame.Text<br>                val btc = frame?.readText() ?: &quot;&quot;<br><br>                onMessage(btc)<br>            }<br>        }.onFailure { error -&gt;<br>            when (error) {<br>                is ClosedReceiveChannelException -&gt; onClose()<br>                else -&gt; onError(error.localizedMessage ?: &quot;Error&quot;)<br>            }<br>        }<br>    }<br><br>    suspend fun close() {<br>        socket?.close(CloseReason(CloseReason.Codes.NORMAL, &quot;Client shutting down.&quot;))<br>        socket = null<br>    }<br>}</pre><p><strong>connect Function</strong>:</p><ul><li>connect function provides to connect WebSocket session and listens incoming messages.</li><li>onMessage(String): Called when a message is received from the server. It passes the message as String.</li><li>onClose(): Called when the WebSocket connection is closed.</li><li>onError(String): Called when an error occurs.</li></ul><p><strong>Receiving Messages in a Loop</strong>:</p><ul><li>socket?.incoming?.receive(): This listens for incoming messages from the WebSocket. incoming is a ReceiveChannel used to receive messages.</li><li>Frame.Text: The code checks if the received message is of type Frame.Text (since WebSocket messages can be text, binary, etc.).</li><li>readText(): If it’s a text frame, it extracts the message content.</li></ul><p><strong>Handling Errors and Connection Closure:</strong></p><ul><li>ClosedReceiveChannelException: This exception is thrown when the WebSocket connection is closed. The onClose() function is called in this case.</li><li>For other types of errors, onError() is called with the localized error message.</li></ul><p><strong>close Function:</strong></p><ul><li>close(): If the socket is open, this method closes it with a specific closure reason.</li></ul><p>Also we can use Flow (using .receiveAsFlow()extension function) for receive data from server. Using Flow makes it easier to handle streams of data in a reactive manner.</p><pre>suspend fun connectWithFlow(): Flow&lt;String&gt; = withContext(Dispatchers.IO){<br>    socket = KtorClient.httpClient.webSocketSession {<br>        url(https://medium.com/&quot;ws://localhost:8080/btc&quot;)<br>    }<br><br>    socket!!<br>        .incoming<br>        .receiveAsFlow()<br>        .map { frame -&gt;<br>            if (frame is Frame.Text) frame.readText() else &quot;&quot;<br>        }<br>        .catch { error -&gt;<br>            when (error) {<br>                is ClosedReceiveChannelException -&gt; emit(&quot;Connection closed.&quot;)<br>                else -&gt; emit(error.localizedMessage ?: &quot;Error&quot;)<br>            }<br>        }<br>}</pre><p>With the data source created, we can now move on to writing the UI code. First, let’s create a ViewModel class to cover the data we will show in the UI and then prepare the data from WebSocket for the UI.</p><pre>class AppViewModel(<br>    private val btcDataSource: WebSocketDataSource<br>): ViewModel() {<br>    private val _cryptoState = MutableStateFlow&lt;List&lt;Double&gt;&gt;(emptyList())<br>    val cryptoState = _cryptoState.asStateFlow()<br><br>    fun collectBtc() {<br>        viewModelScope.launch {<br>            btcDataSource.connect(<br>                onMessage = { btc -&gt;<br>                    val newList = _cryptoState.value.toMutableList()<br>                    newList.add(btc.toDouble())<br>                    _cryptoState.update { newList }<br>                },<br>                onClose = {<br>                    Log.i(&quot;WebSocket&quot;, &quot;Connection closed&quot;)<br>                },<br>                onError = { error -&gt;<br>                    Log.e(&quot;WebSocket&quot;, error)<br>                }<br>            )<br><br>        }<br>    }<br><br>    fun disconnect() {<br>        viewModelScope.launch { btcDataSource.close() }<br>    }<br><br>    override fun onCleared() {<br>        super.onCleared()<br><br>        disconnect()<br>    }<br><br>    companion object {<br>        val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {<br>            @Suppress(&quot;UNCHECKED_CAST&quot;)<br>            override fun &lt;T : ViewModel&gt; create(modelClass: Class&lt;T&gt;): T {<br>                return AppViewModel(WebSocketDataSource()) as T<br>            }<br>        }<br>    }<br>}</pre><blockquote>We disconnect the WebSocket session in onCleared() to prevent memory leaks when the ViewModel is no longer in use.</blockquote><p>It’s time to display this data on the screen with a simple UI:</p><pre>@Composable<br>fun AppScreen(<br>    modifier: Modifier = Modifier,<br>    viewModel: AppViewModel = viewModel(factory = AppViewModel.Factory)<br>) {<br>    val cryptoState by viewModel.cryptoState.collectAsState()<br><br>    Column(<br>        modifier = modifier<br>            .fillMaxSize()<br>            .padding(16.dp)<br>    ) {<br>        LazyColumn(<br>            modifier = Modifier.weight(1f)<br>        ) {<br>            itemsIndexed(items = cryptoState) { index, value -&gt;<br>                Text(<br>                    text = &quot;$value&quot;,<br>                    color = if (value &gt; 0.5) Color.Green else Color.Red,<br>                    modifier = Modifier<br>                        .fillMaxWidth()<br>                        .background(<br>                            color = if (index % 2 == 0) Color.Gray else Color.DarkGray<br>                        )<br>                )<br>            }<br>        }<br><br>        Row(<br>            modifier = Modifier.fillMaxWidth(),<br>            horizontalArrangement = Arrangement.Center<br>        ) {<br>            Button(<br>                onClick = { viewModel.collectBtc() },<br>                content = {<br>                    Text(text = &quot;Connect&quot;)<br>                }<br>            )<br><br>            Button(<br>                onClick = { viewModel.disconnect() },<br>                content = {<br>                    Text(text = &quot;Disconnect&quot;)<br>                }<br>            )<br>        }<br>    }<br>}</pre><p>And result 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79DJg2cJaxgbEmSbNyQbCw.gif" /></figure><p>That’s it! Looks beautiful🤖</p><p><strong><em>Please share your thoughts with me.</em></strong></p><p><strong><em>Thanks for reading!</em></strong></p><p>You can also check these repositories:</p><p><strong>Online Auction App with WebSocket (Ktor Server):</strong></p><p><a href="https://github.com/iamsuatzengin/online-auction-ktor-server-ws">GitHub - iamsuatzengin/online-auction-ktor-server-ws: Online Auction Ktor server using WebSocket</a></p><p><strong>Online Auction App with WebSocket (Android):</strong></p><p><a href="https://github.com/iamsuatzengin/online-auction-android">GitHub - iamsuatzengin/online-auction-android: Online Auction Android application using WebSocket with Ktor client.</a></p><p><strong>Sources:</strong></p><ul><li><a href="https://ktor.io/docs/server-websockets.html">WebSockets | Ktor</a></li><li><a href="https://medium.com/walmartglobaltech/leveraging-web-sockets-for-powering-chat-platforms-38a4629b9688">Leveraging Web sockets for powering chat platforms</a></li><li><a href="https://www.argenova.com.tr/web-socket-api-websockets-nedir">Web Socket API (WebSockets) Nedir?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d28b37cd38a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ktor Client for Android ]]></title>
            <link>https://medium.com/@suatzengin/ktor-client-for-android-7aa3082779a4?source=rss-86a78b9ef5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aa3082779a4</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[ktor]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Suat Zengin]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 14:01:21 GMT</pubDate>
            <atom:updated>2024-03-05T21:46:40.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULSRA0xRa81xbYGA0ZMaeg.png" /></figure><p>Merhaba 👋, bugünkü yazımda Ktor hakkında bilgi vereceğim. Ktor nedir, nerelerde kullanılır, Retrofit ile farkı nedir kısaca bahsedip basit bir örnekle sonlandıracağım. Keyifli okumalar.</p><h4>Ktor nedir?</h4><p><a href="https://ktor.io/docs/welcome.html"><strong>Ktor</strong></a>,<strong> </strong>Kotlin programlama diliyle yazılan, farklı platformlarda kullanabileceğiniz çok yönlü bir çerçevedir. Bu, web uygulamaları, HTTP servisleri ve mobil uygulamalar gibi çeşitli projeleri destekler. Coroutine’ler ile birlikte çalışarak, sağladığı avantajlar ve kolaylıklarla temiz ve etkili kodlar yazılır. Ayrıca Ktor, serialization, authentication, logging gibi işlemleri yapacak, işlevselliği arttıracak çeşitli eklentilere sahiptir.</p><p>Ayrıca Ktor ile sunucu taraflı işlerinizi de yapabilirsiniz. Web uygulamaları, HTTP servisleri geliştirebilirsiniz. Sunucu ve client tarafında soket tabanlı uygulamalar geliştirebilirsiniz.</p><p>Ktor, client tarafta, Android uygulamalarınızda, network’e açılmanızı sağlayan bir çerçeve olarak da kullanılabilir. HTTP isteklerini yönetebilirsiniz. İstekler atıp cevapları kolaylıkla yakalayabilirsiniz. Ktor ile tıpkı hepinizin de yakından tanıdığı Retrofit ve OkHttp gibi popüler kütüphanelerin yaptığı işi yapabilirsiniz.</p><h4><strong>Peki neden Retrofit yerine Ktor?</strong></h4><p>Ktor ile Android uygulamalarınızda Http isteklerini yönetilebileceğini söylemiştim. Ktor bununla sınırlı değildir. Android uygulamalarının ötesine geçerek birden fazla platformda çalışılmasını sağlar. Kotlin Multiplatform projelerinde, birden fazla platformda (Android, iOS, Web, Desktop), tek bir kod tabanında HTTP isteklerinizi yönetebilirsiniz. Bu çok platformlu uyumluluk, özellikle tek bir platform ile sınırlı kalmak istemeyen geliştiriciler için büyük bir avantaj sunar.</p><p>Eğer Retrofit kullanmayı düşünüyorsanız, unutmayın ki Retrofit <em>Java </em>ile yazılmış bir kütüphanedir ve yalnızca Android uygulamalarına özgüdür. Ktor ise çoklu platform desteği sunan, saf Kotlin tabanlı bir çerçeve olarak daha geniş bir yelpazede çalışabilir. Dolayısıyla, birden fazla platform üzerinde projeler geliştirmeyi hedefliyorsanız, Ktor kullanmak mantıklı bir tercih olacaktır.</p><p>Artık bir örnek ile pratik yapma zamanı. Bu örnekte <a href="https://www.boredapi.com/documentation">BoredAPI </a>kullanarak uygulamaya geçelim.</p><p>Öncelikle bağımlılıkları kurarak başlayalım:</p><pre>// build.gradle.kts (module-level)<br>plugins {<br>    //...<br>    id (&quot;kotlinx-serialization&quot;)<br>}<br><br><br>dependencies {<br>    val ktorVersion = &quot;2.3.5&quot;<br>  <br>    implementation(&quot;io.ktor:ktor-client-core:$ktorVersion&quot;)<br>    implementation (&quot;io.ktor:ktor-client-android:$ktorVersion&quot;)<br>    implementation (&quot;io.ktor:ktor-client-logging:$ktorVersion&quot;)<br>    implementation (&quot;io.ktor:ktor-client-content-negotiation:$ktorVersion&quot;)<br>    implementation (&quot;io.ktor:ktor-serialization-kotlinx-json:$ktorVersion&quot;)<br>}</pre><pre>// build.gradle.kts (top-level)<br><br>plugins {<br>    //...<br>    id(&quot;org.jetbrains.kotlin.plugin.serialization&quot;) version (&quot;1.9.0&quot;) apply false<br>}</pre><ul><li><strong>“ktor-client-android”</strong>,<strong> </strong>Android engine bağımlılığıdır. <a href="https://ktor.io/docs/http-client-engines.html">Engine</a>, belirli platformların network isteklerini işlemek için belirli engine’leri olması gerekir. Android spesifik uygulamalarınızda <em>“Android”</em> veya <em>“OkHttp”</em> engine’i kullanabilirsiniz.</li><li><strong>“ktor-client-logging”</strong>, Logging eklentisi için kurulan bir bağımlılıktır. HTTP çağrılarını loglamak için kullanılır.</li><li><strong>“client-content-negotiation”</strong>. ContentNegotiation, istek gönderirken veya yanıt alırken içeriğin belirli formatta serializing/deserializing edilmesini amaçlar.</li><li>JSON bir veriyi serialize/deserialize yapabilmek için kullanacağımız kütüphane: <strong>“</strong><a href="https://github.com/Kotlin/kotlinx.serialization"><strong>kotlinx-serialization</strong></a><strong>”. </strong>Bu kütüphaneyi de HttpClient ayarlarımızı yaparken uygulamamıza entegre edebilmek için ise <strong>“ktor-serialization-kotlinx-json”</strong> bağımlılığını kullanacağız.</li></ul><p>Bağımlılıkların kurulmasının ardından <strong><em>HttpClient</em></strong> kurulumuna geçelim:</p><pre>private val client = HttpClient(Android) {<br><br>    install(ContentNegotiation) {<br>        json(Json {<br>            prettyPrint = true<br>            isLenient = true<br>          })<br>        }<br><br>    install(Logging) {<br>        logger = Logger.DEFAULT<br>        level = LogLevel.BODY<br>    }<br><br>    engine {<br>        connectTimeout = 30_000<br>        socketTimeout = 30_000<br>    }<br>}</pre><ul><li><strong>“Android”</strong> engine sınıfını HttpClient’a parametre olarak geçiyoruz. Ve client ayarlamalarını bir blok açarak yapabiliriz.</li><li>Ayrıca engine ayarları yapmak için <strong>“engine”</strong> metodu kullanabilir.</li><li><strong>“install”</strong> fonksiyonu, <a href="https://ktor.io/docs/http-client-plugins.html">plugin’leri</a> entegre etmemiz için kullanılır. Bir kod bloğu açarak içinde, eklediğimiz plugin’i yapılandırabiliriz.</li><li>İlk olarak serialization plugini olan <a href="https://ktor.io/docs/serialization-client.html">ContentNegotiation</a> kurulumunu yapıyoruz. Hatırla! <strong>ContentNegotiation</strong>, bize gelen içeriğin belirli formatta serialization uygulanmasını sağlar.</li><li>ContentNegotiation, bu belirli formatlar için bir serializer’a ihtiyaç duyar. Bir kod bloğu açıp <strong>“json()”</strong> fonksiyonuna serializer’ımızı kaydediyoruz.</li><li>Bir diğer eklenti (plugin) olan <a href="https://ktor.io/docs/client-logging.html">“Logging”</a> eklentisini kuruyoruz. Bu eklenti ile Http çağrılarımızı loglayabiliriz. Ekstra ayarlamalar yapmak için bir kod bloğu açarak gerekli düzenlemeleri yapabiliriz.</li></ul><p>Client kurulumundan sonra ilk olarak API’dan JSON dönen verimizi Kotlin’de modelleyelim. Random bir aktiviteden dönen JSON formatlı verimiz bu şekildedir:</p><pre>{<br>  &quot;activity&quot;: &quot;Fill out a basketball bracket&quot;,<br>  &quot;type&quot;: &quot;recreational&quot;,<br>  &quot;participants&quot;: 1,<br>  &quot;price&quot;: 0,<br>  &quot;link&quot;: &quot;&quot;,<br>  &quot;key&quot;: &quot;7806284&quot;,<br>  &quot;accessibility&quot;: 0.1<br>}</pre><p>Serialization işlemleri ile uygulamamızın anlayabileceği bir dile çevirmemiz gerekiyor. Kotlin’in serialization kütüphanesi ile bunu yapabiliriz.</p><pre>import kotlinx.serialization.SerialName<br>import kotlinx.serialization.Serializable<br><br>@Serializable<br>data class BoredActivity(<br>    @SerialName(&quot;accessibility&quot;)<br>    val accessibility: Double? = null,<br>    @SerialName(&quot;activity&quot;)<br>    val activity: String? = null,<br>    @SerialName(&quot;key&quot;)<br>    val key: String? = null,<br>    @SerialName(&quot;link&quot;)<br>    val link: String? = null,<br>    @SerialName(&quot;participants&quot;)<br>    val participants: Int? = null,<br>    @SerialName(&quot;price&quot;)<br>    val price: Double? = null,<br>    @SerialName(&quot;type&quot;)<br>    val type: String? = null<br>)</pre><p>Modelimizi de oluşturduğumuza göre artık istek atabiliriz 🥳.</p><p>Direkt URL’i parametre geçerek istek atmak:</p><pre>const val BASE_URL = &quot;http://www.boredapi.com/&quot;<br><br>suspend fun getBoredActivity() : BoredActivity = withContext(Dispatchers.IO) {<br>    val response: HttpResponse = client.get(urlString = &quot;${BASE_URL}api/activity&quot;)<br><br>    val boredActivity = response.body&lt;BoredActivity&gt;()<br><br>    boredActivity<br>}</pre><p>Suspend <a href="https://api.ktor.io/ktor-client/ktor-client-core/io.ktor.client.request/get.html?_ga=2.20779451.265418613.1698348082-1527896084.1695363375&amp;_gl=1*15t9057*_ga*MTUyNzg5NjA4NC4xNjk1MzYzMzc1*_ga_9J976DJZ68*MTY5ODM1MTU5MC40Mi4wLjE2OTgzNTE1OTAuNjAuMC4w"><strong>“get()”</strong></a> fonksiyonu ile <strong>GET </strong>isteklerini işleyebiliriz.</p><blockquote>Girişte de dediğim gibi Ktor, Coroutine’lerden faydalanarak asenkron işlemler yapar.</blockquote><p><strong>“get()”</strong> fonksiyonuna istek atacağımız URL’in tamamını vermek yerine yollarını <strong>(path)</strong> ayrı olarak tek tek de yazabiliriz.</p><pre>val response: HttpResponse = client.get(urlString = BASE_URL) {<br>    url {<br>        appendPathSegments(&quot;api&quot;, &quot;activity&quot;)<br>    }<br>}<br><br>//https://www.boredapi.com/api/activity</pre><p>Bunun yanı sıra <strong>query</strong> string de ekleyebiliriz:</p><pre>val response: HttpResponse = client.get(urlString = BASE_URL) {<br>    url {<br>        // Path param -&gt; BASE_URL/api/activity<br>        appendPathSegments(&quot;api&quot;, &quot;activity&quot;) <br><br>        // Query param -&gt; ..?type=rerecreational<br>        parameters.append(&quot;type&quot;, &quot;recreational&quot;)<br>    }<br>}<br>//https://www.boredapi.com/api/activity?type=recreational</pre><p>Aynı zamanda her istek atımında <strong>BASE_URL</strong>’i vermektense HttpClient ayarlarımızı yaptığımız yerde defaultRequest içinde url() fonksiyonuna geçebiliriz. Artık sadece end-point’ler ile istek atabiliriz.</p><pre>// Service<br>private val client = HttpClient(Android) {<br><br>    defaultRequest {<br>        url(https://medium.com/urlString%20=%20BASE_URL)<br>    }<br><br>    //..<br>    //..<br>}<br><br>// Repository <br>val response: HttpResponse = client.get(&quot;/api/activity&quot;)</pre><p>Eğer <strong>“header”</strong> eklemek isterseniz yine burada eklemek çok kolay olacaktır. Header veya daha fazla bilgi için <a href="https://ktor.io/docs/request.html#headers">buraya </a>tıklayarak ulaşabilirsiniz.</p><p>Şimdi ise sıra geldi kullanıcı ile etkileşime. Network istekleri, local veritabanı işlemleri gibi veriyi ilgilendiren olaylar veri (data) katmanında gerçekleşir. Bu iş mantığı çoğunlukla veri katmanında işlenir ve tüketilmek üzere UI (kullanıcı arayüzü) katmanına gönderilir. Elbette, UI veriyi üreten, bunun üzerinde çeşitli dönüşümler, işlemler yapabilir ancak bu kullanıcı arayüzünün görevinin dışına çıkar ve aynı zamanda okunabilirliği, bakımı ve test edilebilirliği oldukça zorlaştırır.</p><p>Veri katmanından gelen verileri UI katmanında karşılayacak state-holder sınıfımız: ViewModel. ViewModel, kullanıcı arayüzü tarafından tüketilecek durumu (state) tutar ve kullanıcı arayüzüne sunar.</p><blockquote><strong>State</strong>, ViewModel tarafından dönüştürülen, Data katmanından gelen uygulama verileridir.</blockquote><pre>class MainViewModel : ViewModel() {<br><br>    private val _boredActivityState = MutableStateFlow(BoredActivity())<br>    val boredActivityState = _boredActivityState.asStateFlow()<br><br>    init {<br>        getBoredActivity()<br>    }<br><br>    fun getBoredActivity() {<br>        viewModelScope.launch {<br>            val boredActivityList = ApiService().getBoredActivity()<br><br>            _boredActivityState.emit(boredActivityList)<br>        }<br>    }<br>}</pre><p>ViewModel, gelen veriyi kullanıcı arayüzünün tüketeceği forma getirdiğine göre bunları kullanalım artık:</p><pre>/*<br> viewModel()fonksiyonunu kullanabilmek için kurulması gereken bağımlılık:<br><br> implementation(&quot;androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1&quot;)<br>*/<br>@Composable<br>fun BoredActivityScreen(<br>    viewModel: MainViewModel = viewModel()<br>) {<br>    val boredActivity by viewModel.boredActivityState.collectAsState()<br><br>    Column(<br>        modifier = Modifier.fillMaxSize().padding(16.dp),<br>        verticalArrangement = Arrangement.Center,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .background(color = Color.White, shape = RoundedCornerShape(10.dp))<br>                .border(2.dp, color = Color.LightGray, shape = RoundedCornerShape(10.dp))<br>                .clickable { viewModel.getBoredActivity() }<br>                .padding(24.dp)<br>        ) {<br>            Text(<br>                text = boredActivity.activity ?: &quot;Sıkılmaktan sıkıldım!&quot;,<br>                modifier = Modifier.align(alignment = Alignment.Center)<br>            )<br>        }<br>    }<br>}</pre><p>Ekran görüntüsü:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*DXTuDl6GnbMuAniCPbLUYw.png" /><figcaption>App’s screenshot</figcaption></figure><p>Her tıklanmada ise yeni bir istek atarak yeni bir aktivite önerisi alacağız:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWE70AVJoyztoklS6oMklg.gif" /></figure><p>İstekleri başarılı bir şekilde atıp, yanıt aldığımıza göre sona gelmiş bulunuyoruz. Okuduğunuz için teşekkür ederim. Her türlü eleştirinize ve yorumlarınıza açığım.</p><p><strong>Ktor ile ilgili yaptığım bazı projeler:</strong></p><ul><li><a href="https://github.com/iamsuatzengin/fake-store-andro">GitHub - iamsuatzengin/fake-store-andro: &quot;FakeStore Andro&quot; is a mock e-commerce mobile application using Fake-store API designed for educational purposes.</a></li><li><a href="https://github.com/iamsuatzengin/quotes-paging-sample">GitHub - iamsuatzengin/quotes-paging-sample: Paging3 example with Quotes App 🔥</a></li></ul><p><em>Compose Multiplatform</em> örneği:</p><p><a href="https://github.com/iamsuatzengin/news-app-compose-multiplatform">GitHub - iamsuatzengin/news-app-compose-multiplatform</a></p><p><strong>Kaynaklar:</strong></p><p><a href="https://ktor.io/docs/getting-started-ktor-client.html">Creating a client application | Ktor</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aa3082779a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>