<?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 Hazar Duman on Medium]]></title>
        <description><![CDATA[Stories by Hazar Duman on Medium]]></description>
        <link>https://medium.com/@hazardumann0?source=rss-201406708a68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Hazar Duman on Medium</title>
            <link>https://medium.com/@hazardumann0?source=rss-201406708a68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:36:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hazardumann0/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[Jetpack Compose ile Leaderboard Animasyonları]]></title>
            <link>https://medium.com/@hazardumann0/jetpack-compose-ile-leaderboard-animasyonlar%C4%B1-d61aa1e7a165?source=rss-201406708a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61aa1e7a165</guid>
            <category><![CDATA[jetpack-compose-animation]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[leaderboard]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Hazar Duman]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 20:22:41 GMT</pubDate>
            <atom:updated>2025-01-05T20:22:41.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="leaderboard placeholder image" src="https://cdn-images-1.medium.com/max/404/1*gDVK3pUmxZwljYkiwZMThw.png" /></figure><p>Bu yazıda, Jetpack<strong> </strong>Compose kullanarak liderlik tablosunda sıra değişimlerini (yükselme ve düşme) animasyonlarla nasıl görselleştirebileceğimizi ele alıyoruz. Amacımız, sıralama değişikliklerini kullanıcıya etkileyici bir şekilde göstermek. Bunu gerçekleştirmek için offset animasyonlarından faydalanacağız. Sıralama değişiklikleri sırasında sadece kullanıcının değişen kartını değil, bu değişim aralığındaki diğer kartları da hareket ettireceğiz.</p><p>Şimdi, adım adım bu yapıyı nasıl oluşturacağımızı görelim.</p><p><strong>Başlangıç Değerleri</strong></p><p>Öncelikle, animasyonlarda kullanacağımız sabit değerleri ve isim listesini tanımlayalım:</p><pre>const val previousRank = 6<br>const val currentRank = 1<br><br>val rankComponentHeight = 100.dp<br>val gapBetweenCards = 8.dp<br><br>val names = listOf(<br>    &quot;Emily&quot;,<br>    &quot;Michael&quot;,<br>    &quot;Sophia&quot;,<br>    &quot;James&quot;,<br>    &quot;Olivia&quot;,<br>    &quot;William&quot;,<br>    &quot;Emma&quot;<br>)</pre><p>Bu sabitler, gerçek bir uygulamada daha dinamik bir şekilde yönetilebilir (örneğin, bir API veya yerel veritabanından alınabilir). Ancak bu yazıda amacımız işin mantığını açıklamak olduğundan, sabit değerler kullanılmıştır.</p><p><strong>Kart Tasarımı</strong></p><p>Liderlik tablosunda her bir sıralamayı temsil eden bir kart tasarladık. Bu kart, kullanıcının sırasını ve ismini gösterecek:</p><pre>@Composable<br>fun RankCard(<br>    modifier: Modifier = Modifier,<br>    number: Int,<br>    name: String<br>) {<br>    Card(<br>        modifier = modifier,<br>        elevation = CardDefaults.elevatedCardElevation(defaultElevation = 8.dp)<br>    ) {<br>        Row(<br>            modifier = Modifier<br>                .fillMaxWidth()<br>                .height(rankComponentHeight)<br>                .padding(horizontal = 16.dp),<br>            verticalAlignment = Alignment.CenterVertically,<br>            horizontalArrangement = Arrangement.spacedBy(8.dp)<br>        ) {<br>            Text(<br>                text = number.toString(),<br>                style = TextStyle(<br>                    fontWeight = FontWeight.Bold,<br>                    fontSize = 32.sp<br>                )<br>            )<br>            Text(text = name)<br>        }<br>    }<br>}</pre><p>Bu bileşen, her bir sıralama için sade bir görünüm sağlar. Kartların liste halinde nasıl göründüğünü aşağıdaki görselde görebilirsiniz:</p><figure><img alt="RankCard image" src="https://cdn-images-1.medium.com/max/300/1*BaXL34IYR5NVyHqQ-8CZhA.png" /></figure><p><strong>Offset Hesaplaması ve Yardımcı Fonksiyonlar</strong></p><p>Kullanıcının eski ve güncel sıralamaları arasındaki hareketi hesaplayabilmek için bir <strong>offset</strong> değeri belirlememiz gerekiyor. Bu, sıralama farkını dikkate alarak kartların doğru konuma taşınmasını sağlar. İşte bu hesaplama için kullanacağımız fonksiyon:</p><pre>@Composable<br>fun calculateOffsetY(currentRank: Int, previousRank: Int): Float {<br>    val rankDifference = (currentRank - previousRank).absoluteValue<br>    val totalGapBetweenCards = rankDifference * gapBetweenCards.toPx()<br>    val totalHeight = rankDifference * rankComponentHeight.toPx()<br>    val totalOffset = totalGapBetweenCards + totalHeight<br><br>    return if (currentRank &gt; previousRank) -totalOffset else totalOffset<br>}</pre><p><strong>Açıklama:</strong></p><p>1. rankDifference: Eski ve yeni sıralama arasındaki fark.</p><p>2. totalGapBetweenCards: Kartlar arasındaki boşluğun toplam değeri.</p><p>3. totalHeight: Kartların yüksekliği dikkate alınarak hesaplanan toplam yükseklik.</p><p>4. totalOffset: Yukarıda hesaplanan boşluk ve yükseklik değerlerinin toplamı.</p><p>5. Sonuç olarak, sıralama değişim yönüne göre bu toplam değer pozitif ya da negatif olarak döndürülür.</p><p><strong>Float ve Dp Dönüşümleri İçin Yardımcı Fonksiyonlar</strong></p><p>Jetpack Compose, <strong>dp</strong> ve <strong>px</strong> birimleri arasında dönüşüm yapmak için yerleşik araçlar sunar. Ancak, kullanım kolaylığı sağlamak adına aşağıdaki yardımcı <strong>extension</strong> fonksiyonlarını tanımlayabiliriz:</p><pre>@Composable<br>fun Float.toDp(): Dp {<br>    val density = LocalDensity.current<br>    return with(density) { this@toDp.toDp() }<br>}<br><br>@Composable<br>fun Dp.toPx(): Float {<br>    val density = LocalDensity.current<br>    return with(density) { this@toPx.toPx() }<br>}</pre><p>• Float.toDp(): Float türündeki bir değeri Dp birimine dönüştürür.</p><p>• Dp.toPx(): Dp birimindeki bir değeri Float türünde px birimine dönüştürür.</p><p><strong>Offset Animasyonu için Component</strong></p><p>Sıralama değişimlerinde kartların hareketini görselleştirmek için bir component oluşturuyoruz. Bu bileşen, dışarıdan hesaplanan <strong>offset</strong> değerini alır ve belirli bir süre boyunca animasyonu uygular.</p><pre>@Composable<br>fun OffsetYAnimator(<br>    modifier: Modifier = Modifier,<br>    initialOffsetY: Float = 0f,<br>    content: @Composable () -&gt; Unit<br>) {<br>    val currentOffset = remember { Animatable(initialOffsetY) }<br><br>    LaunchedEffect(initialOffsetY) {<br>        currentOffset.animateTo(<br>            targetValue = 0f,<br>            animationSpec = tween(durationMillis = 3000)<br>        )<br>    }<br><br>    Box(modifier.offset(y = currentOffset.value.toDp())) {<br>        content()<br>    }<br>}</pre><p>1. initialOffsetY: Kartın başlangıçtaki offset (dikey kaydırma) değeri.</p><p>2. Animatable: Offset değerini animasyonla kontrol etmek için kullanılıyor.</p><p>3. LaunchedEffect: Offset değerindeki değişiklikleri dinler ve animasyonu başlatır.</p><p>4. animateTo: Offset değerini belirlenen bir süre (örneğin 3000 milisaniye) içinde sıfır değerine doğru animasyonla taşır.</p><p>5. Box: Kartı offset değeriyle hareket ettirirken içinde verilen içeriği (content) barındırır.</p><p>Bu component, animasyonun dinamik ve esnek bir şekilde uygulanmasını sağlar. Animasyon, kartın bulunduğu başlangıç pozisyonundan sıfır offset değerine doğru hareket etmesini sağlar. Bu, kullanıcı deneyimini daha akıcı hale getirir.</p><p>Şimdiye kadar animasyonun temel bileşenlerini ve mantığını oluşturduk. Sıra, bu bileşenleri bir araya getirerek bir liderlik tablosu iskeleti oluşturmaya geldi.</p><p><strong>İskelet Yapı</strong></p><p>Liderlik tablosunu oluşturmak için aşağıdaki <strong>Column</strong> yapısını kullanıyoruz:</p><pre>val scrollState = rememberScrollState()<br><br>Column(<br>    Modifier<br>        .fillMaxSize()<br>        .verticalScroll(scrollState)<br>        .padding(16.dp),<br>    verticalArrangement = Arrangement.spacedBy(gapBetweenCards)<br>) {<br>    repeat(names.size) { index -&gt;<br>        val rank = index + 1<br>        val offsetType = decideAnimationType(rank, currentRank, previousRank)<br>        val offsetY = when (offsetType) {<br>            OffsetAnimationType.CURRENT_POSITION -&gt; calculateOffsetY(currentRank, previousRank)<br>            OffsetAnimationType.SHIFTING_DOWN -&gt; rankComponentHeight.toPx()<br>            OffsetAnimationType.SHIFTING_UP -&gt; -rankComponentHeight.toPx()<br>            else -&gt; 0f<br>        }<br><br>        OffsetYAnimator(<br>            modifier = if (offsetType == OffsetAnimationType.CURRENT_POSITION) Modifier.zIndex(2f) else Modifier,<br>            initialOffsetY = offsetY<br>        ) {<br>            RankCard(<br>                modifier = Modifier,<br>                number = rank,<br>                name = names[index]<br>            )<br>        }<br>    }<br>}</pre><p><strong>LazyColumn Neden Kullanılmadı?</strong></p><p>Bu yapıda <strong>LazyColumn</strong> yerine <strong>Column</strong> tercih edilmesinin sebebi, <strong>LazyColumn</strong>’un sadece görünür alandaki öğeleri bellekte tutmasıdır. Bu durum, uzun bir listede animasyonların doğru çalışmasını engelleyebilir. <strong>Column</strong> kullanılarak, tüm öğeler bellekte tutulur ve animasyonların her biri doğru şekilde uygulanır. Ancak bu çözüm, uzun listelerde performans kaybına neden olabilir. Daha büyük verilerle çalışırken dikkat edilmelidir.</p><p><strong>Animasyon Gösterimi</strong></p><figure><img alt="rank up animation" src="https://cdn-images-1.medium.com/max/1024/1*nGCXr5_EqH95M5YuBJTh6g.gif" /></figure><p><strong>Sonuç</strong></p><p>Bu yazıda, Jetpack<strong> </strong>Compose kullanarak bir leaderboard için animasyon yapısını detaylandırdık. Animasyonlar, sıralama değişikliklerini etkileyici bir şekilde kullanıcıya sunmak için tasarlandı. Sıralama değişikliklerini göstermek için offset animasyonlarından faydalanarak sadece sırası değişen kartı değil, diğer kartları da hareket ettirerek akıcı bir kullanıcı deneyimi sağladık.</p><p>Oluşturduğumuz yapı, küçük ve orta ölçekli projelerde etkili bir şekilde kullanılabilir. Daha dinamik ve büyük veri setleriyle çalışmak için sabit veriler yerine API ya da yerel kaynaklardan veri almak ve ek optimizasyonlar uygulamak yapıyı daha esnek hale getirebilir.</p><p>Sonuç olarak, bu yazıda ele alınan yöntemler, leaderboard uygulamalarında sıralama değişikliklerini görselleştirmek ve kullanıcı deneyimini zenginleştirmek isteyen projeler için güçlü bir temel sunmaktadır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61aa1e7a165" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android’de Test Yazarken Kullanılabilecek Faydalı Metotlar]]></title>
            <link>https://medium.com/@hazardumann0/androidde-test-yazarken-kullan%C4%B1labilecek-faydal%C4%B1-metotlar-a2d8a286908a?source=rss-201406708a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d8a286908a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[junit4]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[mockk]]></category>
            <dc:creator><![CDATA[Hazar Duman]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 20:05:56 GMT</pubDate>
            <atom:updated>2025-01-04T20:05:56.179Z</atom:updated>
            <content:encoded><![CDATA[<p>Android projelerinde test yazmak, kod kalitesini artırır ve bakım sürecini kolaylaştırır. JUnit4 ve MockK gibi kütüphaneler sayesinde, özellikle coroutine tabanlı testleri yazmak daha pratik hale gelir. Bu yazıda, <strong>coEvery</strong>, <strong>coAnswers</strong>, <strong>coJustRun</strong> gibi MockK metotlarından ve JUnit’in temel <strong>assert</strong> fonksiyonlarından bahsederek örnek kod parçaları paylaşacağım.</p><p><strong>coEvery, coAnswers, coJustRun<br></strong>MockK, coroutine tabanlı Android projelerinde test yazmayı kolaylaştıran çeşitli metotlar sunar:</p><p>• <strong>coEvery</strong>: belirli bir coroutine fonksiyonunun nasıl bir değer döndüreceğini veya ne şekilde davranacağını belirtmek için kullanılır.</p><p>• <strong>coAnswers</strong>: coEvery ile benzer şekilde yanıtı düzenlemeye yarar; birden fazla yanıt veya parametreye göre farklı sonuçlar dönmesi isteniyorsa ek esneklik sağlar.</p><p>• <strong>coJustRun</strong>: Sonuç döndürmeyen coroutine fonksiyonlarının çalışmasını simüle eder.</p><pre>class MyRepository {<br>    suspend fun fetchData(): String {<br>        // Gerçek ağ çağrısı veya veri işlemleri<br>        return &quot;Original data&quot;<br>    }<br>}<br><br>@Test<br>fun `fetchData is mocked successfully`() = runTest {<br>    val repository = mockk&lt;MyRepository&gt;()<br><br>    coEvery { repository.fetchData() } returns &quot;Sample data&quot;<br><br>    val result = repository.fetchData()<br>    assertEquals(&quot;Sample data&quot;, result)<br>}</pre><p>Bu örnekte, coEvery ile fetchData çağrısının “Sample data” döndüreceğini ayarladık, ardından test içinde aldığımız sonucu <strong>assertEquals</strong>ile doğruladık.</p><p><strong>JUnit’in Temel Asserter Fonksiyonları</strong></p><p>JUnit4, testlerde sıkça ihtiyaç duyulan doğrulamalar için temel asserter fonksiyonları sunar. Aşağıda bu metotların temel kullanımları ve ne amaçla kullanıldıkları belirtilmiştir</p><p>• <strong>assertTrue(condition): </strong>Koşulun doğru (true) olması beklendiğinde kullanılır.</p><pre>assertTrue(value &gt; 5)</pre><p>• <strong>assertFalse(condition): </strong>Koşulun yanlış (false) olması beklendiğinde kullanılır.</p><p>• <strong>assertEquals(expected, actual): </strong>Beklenen (expected) ve gerçek (actual) değerlerin eşit olup olmadığını karşılaştırır.</p><pre>assertEquals(&quot;Hello&quot;, greetingText)</pre><p>• <strong>assertNull(value): </strong>Değerin null olup olmadığını kontrol eder.</p><p>• <strong>assertNotNull(value): </strong>Değerin null olmamasını kontrol eder.</p><p>• <strong>assertSame(expected, actual): </strong>İki ifadenin bellekte aynı referansa sahip olup olmadığını denetler.</p><pre>val obj = Any()<br>val ref = obj<br>assertSame(obj, ref)</pre><ul><li><strong>assertNotSame(expected, actual): </strong>İki ifadenin farklı referanslara sahip olup olmadığını denetler.</li></ul><p>Bu metotlar, test senaryolarında kodun beklenen şekilde çalışıp çalışmadığını anlamamızı sağlar. Her biri farklı bir kontrol amacına hizmet ederek uygulamamızın mantığını daha kapsamlı test etme olanağı sunar.</p><p><strong>Örnek Senaryo</strong></p><pre>class MyViewModel(private val repository: MyRepository) {<br><br>    suspend fun getWelcomeMessage(): String {<br>        val data = repository.fetchData()<br>        return if (data.isNotBlank()) {<br>            &quot;Data received: $data&quot;<br>        } else {<br>            &quot;No data found!&quot;<br>        }<br>    }<br>}<br><br>class MyViewModelTest {<br><br>    private val repository = mockk&lt;MyRepository&gt;()<br>    private val viewModel = MyViewModel(repository)<br><br>    @Test<br>    fun `when repository returns valid data, welcome message is shown`() = runTest {<br>        coEvery { repository.fetchData() } returns &quot;Test info&quot;<br><br>        val message = viewModel.getWelcomeMessage()<br>        assertEquals(&quot;Data received: Test info&quot;, message)<br>    }<br><br>    @Test<br>    fun `when repository returns blank, error message is shown`() = runTest {<br>        coEvery { repository.fetchData() } returns &quot;&quot;<br><br>        val message = viewModel.getWelcomeMessage()<br>        assertEquals(&quot;No data found!&quot;, message)<br>    }<br>}</pre><p>Bu örnekte, ViewModel içindeki mantığı test ederken Repository’yi mock’layarak gerçek ağa çıkmadan veri işlemlerini hızlı ve güvenilir biçimde test edebiliyoruz.</p><p><strong>Sonuç</strong></p><p>Bu yazıda, coroutine tabanlı Android testlerinde kullanılan <strong>coEvery</strong>, <strong>coAnswers </strong>gibi MockK metotlarını ve JUnit’in temel asserter fonksiyonlarını inceledik.</p><p>• MockK sayesinde farklı parametre ve dönüş değerlerini simüle etmek daha kolay hale geliyor.</p><p>• JUnit asserter fonksiyonlarıyla da çeşitli durumları (null kontrolleri, referans eşitliği, değer eşitliği gibi) test edebiliyoruz.</p><p>Düzenli test yazma alışkanlığı, uygulamanın daha kararlı bir yapıya sahip olmasına ve gelecekteki sürümlerde ortaya çıkabilecek hataların daha erken tespit edilmesine yardımcı olur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d8a286908a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter’da Riverpod Kullanarak Sürdürülebilir State Yönetimi]]></title>
            <link>https://medium.com/@hazardumann0/flutterda-riverpod-kullanarak-s%C3%BCrd%C3%BCr%C3%BClebilir-state-y%C3%B6netimi-32597989a0a0?source=rss-201406708a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/32597989a0a0</guid>
            <category><![CDATA[cross-platform]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[riverpod]]></category>
            <dc:creator><![CDATA[Hazar Duman]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 14:02:17 GMT</pubDate>
            <atom:updated>2024-12-15T14:02:17.636Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter uygulamanız büyüdükçe, arka planda dönen verileri kontrol etmek bazen zorlaşıyor. İşte Riverpod, bu zorluğu aşmak için müthiş bir araç. Anlaşılır yapısıyla kodlarınızı daha temiz hale getiriyor.</p><p>Aşağıda Riverpod’un temel kavramlarını, yapılarını ve bazı örnek kullanım şekillerini bulacaksınız. Umarım bu bilgiler, projelerinizde daha rahat ilerlemenizi sağlar.</p><p><strong>Projeye Riverpod Dahil Etmek</strong></p><p>Riverpod’u projenize eklemek için tek yapmanız gereken terminalde şu komutu çalıştırmak:</p><pre>flutter pub add flutter_riverpod</pre><p>Ardından import ‘package:flutter_riverpod/flutter_riverpod.dart’; satırıyla Riverpod’u kodlarınıza dahil edebilirsiniz.</p><p><strong>ProviderScope ile Temel Altyapı</strong></p><p>Riverpod, provider adını verdiğimiz yapılarla veri yönetir. Bu provider’ların güvenle çalışabilmesi için uygulamanızı ProviderScope isimli bir widget’la sarmanız gerekir. Genellikle bu, main.dart dosyasındaki runApp çağrısında yapılır:</p><pre>void main() {<br>  runApp(<br>    ProviderScope(<br>      child: MyApp(),<br>    ),<br>  );<br>}</pre><p>Bundan sonra dilediğiniz yerde provider’larınızı tanımlayabilir ve kullanabilirsiniz.</p><p><strong>Provider Çeşitleri</strong></p><p>Riverpod birçok provider tipi sunar:</p><ul><li><strong>Provider:</strong> Sabit, değişmeyen bir değer sağlamak için idealdir.</li></ul><pre>final greetingProvider = Provider&lt;String&gt;((ref) =&gt; &quot;Merhaba!&quot;);</pre><ul><li><strong>StateProvider:</strong> Değişken, basit state değerlerini yönetir.</li></ul><pre>final counterProvider = StateProvider&lt;int&gt;((ref) =&gt; 0);</pre><ul><li><strong>FutureProvider:</strong> Asenkron veri işlemlerini (API çağrıları gibi) kolayca yönetir.</li></ul><pre>final userNameProvider = FutureProvider&lt;String&gt;((ref) async {<br>  await Future.delayed(Duration(seconds: 2));<br>  return &quot;FlutterUser42&quot;;<br>});</pre><p>• <strong>StreamProvider:</strong> Gerçek zamanlı veri akışlarını (sohbet mesajları, sensör verileri) dinlemek için kullanılır.</p><p>• <strong>ChangeNotifierProvider / StateNotifierProvider:</strong> Daha karmaşık iş mantıklarını yönetmek için bu yapıları tercih edebilirsiniz. Hem Flutter’ın yerleşik ChangeNotifier mantığıyla hem de Riverpod’un StateNotifier yapısıyla uyumlu çalışır.</p><p>Bu sayede her senaryo için uygun bir provider tipi bulabilirsiniz.</p><p><strong>Provider Verilerini Tüketme</strong></p><p>Verilerinizi ekranda göstermek için ConsumerWidget, ConsumerStatefulWidget veya Consumer yapılarından yararlanabilirsiniz.</p><ul><li><strong>ConsumerWidget:</strong> Stateless bir widget gibi davranır, ancak build metodu WidgetRef ref parametresi alır. Bu sayede ref.watch ve ref.read fonksiyonlarını kullanabilir, provider verilerini kolayca ekrana yansıtırsınız.</li></ul><pre>class GreetingPage extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final greeting = ref.watch(greetingProvider);<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Provider Örneği&quot;)),<br>      body: Center(child: Text(greeting)),<br>    );<br>  }<br>}</pre><ul><li><strong>ConsumerStatefulWidget:</strong> Stateful yapıya ihtiyacınız varsa kullanın. Bu da benzer şekilde ref üzerinden provider değerlerini izleme imkânı sunar.</li><li><strong>Consumer:</strong> Sadece belli bir widget ağacı dalında provider verisi dinlemek istiyorsanız Consumer kullanarak o bölümü kapsayabilirsiniz.</li></ul><p><strong>Örnek: Sayaç Uygulaması</strong></p><p>Basit bir sayaç uygulamasıyla StateProvider kullanımını görelim:</p><pre>final counterProvider = StateProvider&lt;int&gt;((ref) =&gt; 0);<br><br>class CounterPage extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final count = ref.watch(counterProvider);<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Sayaç&quot;)),<br>      body: Center(child: Text(&quot;$count&quot;, style: TextStyle(fontSize: 48))),<br>      floatingActionButton: FloatingActionButton(<br>        onPressed: () =&gt; ref.read(counterProvider.notifier).state++,<br>        child: Icon(Icons.add),<br>      ),<br>    );<br>  }<br>}</pre><p>Her tıklamada değer artar, widget otomatik olarak güncellenir.</p><p><strong>Asenkron Verilerle Çalışma</strong></p><p>FutureProvider kullanarak asenkron işlemleri yönetmek çok kolay:</p><pre>final userNameProvider = FutureProvider&lt;String&gt;((ref) async {<br>  await Future.delayed(Duration(seconds: 2));<br>  return &quot;FlutterUser42&quot;;<br>});<br><br>class AsyncPage extends ConsumerWidget {<br>  @override<br>  Widget build(BuildContext context, WidgetRef ref) {<br>    final asyncValue = ref.watch(userNameProvider);<br><br>    return Scaffold(<br>      appBar: AppBar(title: Text(&quot;Asenkron Örnek&quot;)),<br>      body: Center(<br>        child: asyncValue.when(<br>          data: (value) =&gt; Text(&quot;Kullanıcı adı: $value&quot;),<br>          loading: () =&gt; CircularProgressIndicator(),<br>          error: (err, _) =&gt; Text(&quot;Hata: $err&quot;),<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Bu sayede yükleniyor, hata ve başarılı durumlarını tek bir noktadan yönetebilirsiniz.</p><p><strong>Sonuç</strong></p><p>Riverpod, Flutter uygulamalarında state yönetimini kolaylaştıran güçlü bir araçtır. Sağladığı esneklik, provider çeşitliliği ve basit kullanımı sayesinde, uygulamanızın büyüklüğü ne olursa olsun düzenli bir yapı oluşturmanıza yardımcı olur.</p><p>Hem sabit hem de dinamik verilerle çalışırken Riverpod, temiz ve anlaşılır bir çözüm sunar. Karmaşıklığı azaltan bu yaklaşımı projelerinizde deneyerek farkı hissedebilirsiniz. Daha düzenli ve bakımı kolay uygulamalar için Riverpod harika bir seçimdir. Keyifli çalışmalar!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32597989a0a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the MVI Design Pattern in Android Development with Kotlin and Jetpack Compose]]></title>
            <link>https://medium.com/@hazardumann0/understanding-the-mvi-design-pattern-in-android-development-with-kotlin-and-jetpack-compose-5a5b96972968?source=rss-201406708a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a5b96972968</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mvi]]></category>
            <dc:creator><![CDATA[Hazar Duman]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 11:49:20 GMT</pubDate>
            <atom:updated>2024-07-15T11:51:29.008Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In Android development, design patterns play a crucial role in managing the complexity of building scalable and maintainable applications. Among the various patterns available, the Model-View-Intent (MVI) design pattern is noteworthy due to its unidirectional data flow and the clarity it brings to state management. This article explores the MVI pattern, demonstrating its implementation using Kotlin and Jetpack Compose for building intuitive user interfaces with complex state management.</p><p><strong>What is MVI?</strong></p><p>Model-View-Intent (MVI) is a design pattern inspired by the unidirectional data flow found in reactive programming. It ensures a clear separation of concerns and simplifies state management by dividing the application into three distinct components:</p><p>1. <strong>Model</strong>: Represents the state of the application.</p><p>2. <strong>View</strong>: Displays the state and interacts with the user.</p><p>3. <strong>Intent</strong>: Captures user actions and translates them into state changes.</p><p><strong>Key Characteristics of MVI</strong></p><p>• <strong>Unidirectional Data Flow</strong>: Data flows in a single direction, making the state changes predictable and easier to debug.</p><p>• <strong>Immutable State</strong>: The state is immutable, ensuring that every change results in a new state.</p><p>• <strong>Single Source of Truth</strong>: The state is managed centrally, providing a single source of truth for the entire application.</p><p><strong>Implementing MVI in an Android Application<br></strong>To demonstrate MVI, we will build a simple shopping cart application using Kotlin and Jetpack Compose.</p><p><strong>Step 1: Setting Up the Project<br></strong>Start by creating a new Android project with Jetpack Compose enabled. Add the necessary dependencies to your build.gradle file:</p><pre>dependencies {<br>    implementation &quot;androidx.compose.ui:ui:1.0.1&quot;<br>    implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:2.3.1&quot;<br>    implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0&quot;<br>}</pre><p><strong>Step 2: Defining the Model<br></strong>The Model represents the state of our application. For the shopping cart app, the state includes a list of items, the total price, loading status, and any error messages.</p><pre>data class CartState(<br>    val items: List&lt;CartItem&gt; = emptyList(),<br>    val total: Double = 0.0,<br>    val isLoading: Boolean = false,<br>    val errorMessage: String? = null<br>)<br><br>data class CartItem(<br>    val id: String,<br>    val name: String,<br>    val price: Double,<br>    val quantity: Int<br>)</pre><p><strong>Step 3: Defining the Intents<br></strong>Intents represent the actions that can change the state. In our case, we have actions for loading the cart, adding items, removing items, updating item quantities, and showing errors.</p><pre>sealed class CartIntent {<br>    object LoadCart : CartIntent()<br>    data class AddItem(val item: CartItem) : CartIntent()<br>    data class RemoveItem(val itemId: String) : CartIntent()<br>    data class UpdateQuantity(val itemId: String, val quantity: Int) : CartIntent()<br>    data class ShowError(val message: String) : CartIntent()<br>}</pre><p><strong>Step 4: Implementing the ViewModel<br></strong>The ViewModel handles the state changes based on the intents. It maintains the state and processes intents to update the state accordingly.</p><pre>class CartViewModel : ViewModel() {<br>    private val _state = MutableStateFlow(CartState())<br>    val state: StateFlow&lt;CartState&gt; get() = _state<br><br>    fun processIntent(intent: CartIntent) {<br>        when (intent) {<br>            is CartIntent.LoadCart -&gt; loadCart()<br>            is CartIntent.AddItem -&gt; addItem(intent.item)<br>            is CartIntent.RemoveItem -&gt; removeItem(intent.itemId)<br>            is CartIntent.UpdateQuantity -&gt; updateQuantity(intent.itemId, intent.quantity)<br>            is CartIntent.ShowError -&gt; showError(intent.message)<br>        }<br>    }<br><br>    private fun loadCart() {<br>        viewModelScope.launch {<br>            _state.value = _state.value.copy(isLoading = true)<br>            try {<br>                // Simulate loading cart items<br>                val items = listOf(<br>                    CartItem(&quot;1&quot;, &quot;Item 1&quot;, 10.0, 1),<br>                    CartItem(&quot;2&quot;, &quot;Item 2&quot;, 20.0, 2)<br>                )<br>                _state.value = _state.value.copy(items = items, total = items.sumOf { it.price * it.quantity }, isLoading = false)<br>            } catch (e: Exception) {<br>                _state.value = _state.value.copy(isLoading = false)<br>                processIntent(CartIntent.ShowError(e.message ?: &quot;Unknown error&quot;))<br>            }<br>        }<br>    }<br><br>    private fun addItem(item: CartItem) {<br>        val items = _state.value.items.toMutableList().apply { add(item) }<br>        _state.value = _state.value.copy(items = items, total = items.sumOf { it.price * it.quantity })<br>    }<br><br>    private fun removeItem(itemId: String) {<br>        val items = _state.value.items.filter { it.id != itemId }<br>        _state.value = _state.value.copy(items = items, total = items.sumOf { it.price * it.quantity })<br>    }<br><br>    private fun updateQuantity(itemId: String, quantity: Int) {<br>        val items = _state.value.items.map {<br>            if (it.id == itemId) it.copy(quantity = quantity) else it<br>        }<br>        _state.value = _state.value.copy(items = items, total = items.sumOf { it.price * it.quantity })<br>    }<br><br>    private fun showError(message: String) {<br>        _state.value = _state.value.copy(errorMessage = message)<br>    }<br>}</pre><p><strong>Step 5: Creating the View<br></strong>Using Jetpack Compose, we will create the UI that displays the cart items, total price, and provides buttons to add, remove, and update items.</p><pre>@Composable<br>fun CartScreen(viewModel: CartViewModel) {<br>    val state by viewModel.state.collectAsState()<br><br>    Column(<br>        modifier = Modifier.fillMaxSize().padding(16.dp),<br>        verticalArrangement = Arrangement.Top,<br>        horizontalAlignment = Alignment.CenterHorizontally<br>    ) {<br>        if (state.isLoading) {<br>            CircularProgressIndicator()<br>        } else {<br>            state.items.forEach { item -&gt;<br>                Row(<br>                    modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),<br>                    horizontalArrangement = Arrangement.SpaceBetween,<br>                    verticalAlignment = Alignment.CenterVertically<br>                ) {<br>                    Text(text = item.name)<br>                    Row {<br>                        IconButton(onClick = { viewModel.processIntent(CartIntent.RemoveItem(item.id)) }) {<br>                            Icon(Icons.Default.Delete, contentDescription = &quot;Remove&quot;)<br>                        }<br>                        Text(text = &quot;${item.quantity} x ${item.price}&quot;)<br>                        IconButton(onClick = { viewModel.processIntent(CartIntent.UpdateQuantity(item.id, item.quantity + 1)) }) {<br>                            Icon(Icons.Default.Add, contentDescription = &quot;Increment&quot;)<br>                        }<br>                    }<br>                }<br>            }<br>            Text(text = &quot;Total: ${state.total}&quot;, style = MaterialTheme.typography.h5)<br>            Button(onClick = { viewModel.processIntent(CartIntent.LoadCart) }) {<br>                Text(&quot;Load Cart&quot;)<br>            }<br>            Button(onClick = { <br>                val newItem = CartItem(&quot;3&quot;, &quot;Item 3&quot;, 15.0, 1)<br>                viewModel.processIntent(CartIntent.AddItem(newItem)) <br>            }) {<br>                Text(&quot;Add Item&quot;)<br>            }<br>        }<br>        state.errorMessage?.let { error -&gt;<br>            Text(text = error, color = Color.Red)<br>        }<br>    }<br>}</pre><p><strong>Step 6: Setting Up the Main Activity<br></strong>Finally, set up the MainActivity to display the CartScreen.</p><pre>class MainActivity : ComponentActivity() {<br>    private val viewModel: CartViewModel by viewModels()<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            MaterialTheme {<br>                CartScreen(viewModel)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Testing MVI Components</strong></p><p>Testing MVI components is crucial to ensure the reliability of the application. Each component should be independently testable.</p><p><strong>Unit Testing the ViewModel</strong></p><p>Example unit tests for the ViewModel:</p><pre>class CartViewModelTest {<br><br>    private lateinit var viewModel: CartViewModel<br><br>    @Before<br>    fun setUp() {<br>        viewModel = CartViewModel()<br>    }<br><br>    @Test<br>    fun testInitialState() {<br>        val initialState = viewModel.state.value<br>        assertEquals(0, initialState.items.size)<br>        assertEquals(0.0, initialState.total, 0.01)<br>        assertEquals(false, initialState.isLoading)<br>        assertNull(initialState.errorMessage)<br>    }<br><br>    @Test<br>    fun testLoadCart() = runBlocking {<br>        viewModel.processIntent(CartIntent.LoadCart)<br>        val state = viewModel.state.first { !it.isLoading }<br>        assertEquals(2, state.items.size)<br>        assertEquals(50.0, state.total, 0.01)<br>        assertEquals(false, state.isLoading)<br>    }<br><br>    @Test<br>    fun testShowError() {<br>        val errorMessage = &quot;Error occurred&quot;<br>        viewModel.processIntent(CartIntent.ShowError(errorMessage))<br>        val state = viewModel.state.value<br>        assertEquals(errorMessage, state.errorMessage)<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>The MVI design pattern enhances the development process in Android applications by introducing a structured and predictable way to manage state. Its unidirectional data flow and immutable state management ensure that applications remain easy to debug and maintain. By utilizing Kotlin and Jetpack Compose, developers can create responsive and scalable user interfaces that handle complex state changes efficiently. The shopping cart application example demonstrates how MVI can be implemented to manage various user interactions and asynchronous operations effectively. Moreover, incorporating thorough testing practices ensures that each component functions correctly and reliably, leading to more robust and dependable applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a5b96972968" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding WorkManager in Android: A Comprehensive Guide]]></title>
            <link>https://medium.com/@hazardumann0/understanding-workmanager-in-android-a-comprehensive-guide-1cdb9f2b9f90?source=rss-201406708a68------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdb9f2b9f90</guid>
            <dc:creator><![CDATA[Hazar Duman]]></dc:creator>
            <pubDate>Sun, 26 May 2024 13:35:52 GMT</pubDate>
            <atom:updated>2024-05-26T13:37:32.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flIZ4WoJ1tj3Gsb04OKVZQ.png" /></figure><p>In Android development, managing background tasks efficiently and reliably is crucial. WorkManager, a part of Android Jetpack, is a powerful API designed for this purpose. It allows you to define and schedule tasks that need to run under specific conditions or at particular times, ensuring they persist even across device reboots.</p><h3>Key Features of WorkManager</h3><ul><li>Persistent Tasks: WorkManager ensures that tasks are executed even if the device is restarted.</li><li>Task Constraints: You can define conditions under which tasks should run, such as only when the device is charging or connected to Wi-Fi.</li><li>Task Chaining: It allows you to create a sequence of dependent tasks that execute in a defined order.</li><li>API Level Compatibility: WorkManager operates independently of API level, making it compatible with a wide range of devices.</li><li>Backward Compatibility: It supports devices running Android 4.0 (API Level 14) and above.</li></ul><h3>How to Use WorkManager</h3><ul><li><strong>Adding Dependencies</strong>: First, you need to add the WorkManager library to your build.gradle file.</li></ul><pre>dependencies {<br>    implementation (&quot;androidx.work:work-runtime-ktx:2.9.0&quot;)<br>}</pre><ul><li><strong>Defining a Task</strong>: Define a task by creating a class that extends the Worker class.</li></ul><pre>class MyWorker(appContext: Context, workerParams: WorkerParameters) :<br>        Worker(appContext, workerParams) {<br><br>    override fun doWork(): Result {<br>        // Define the task to be executed here<br>        return Result.success()<br>    }<br>}</pre><ul><li><strong>Scheduling the Task</strong>: Use WorkRequest to specify when and under what conditions the task should run.</li></ul><pre>val myWorkRequest = OneTimeWorkRequestBuilder&lt;MyWorker&gt;()<br>    .setConstraints(<br>        Constraints.Builder()<br>            .setRequiredNetworkType(NetworkType.CONNECTED)<br>            .build()<br>    )<br>    .build()<br><br>WorkManager<br>    .getInstance(context)<br>    .enqueue(myWorkRequest)</pre><h3>Periodic Work with WorkManager</h3><p>In addition to one-time tasks, WorkManager also supports periodic tasks. These are tasks that need to be executed at regular intervals. This is achieved using PeriodicWorkRequest.</p><pre>val periodicWorkRequest = PeriodicWorkRequestBuilder&lt;MyWorker&gt;(15, TimeUnit.MINUTES)<br>    .setConstraints(<br>        Constraints.Builder()<br>            .setRequiredNetworkType(NetworkType.CONNECTED)<br>            .build()<br>    )<br>    .build()<br><br>WorkManager<br>    .getInstance(context)<br>    .enqueueUniquePeriodicWork(<br>        &quot;MyPeriodicWork&quot;,<br>        ExistingPeriodicWorkPolicy.KEEP,<br>        periodicWorkRequest<br>    )</pre><p>In this example, the task will run every 15 minutes, but you can adjust the interval as needed. Note that the minimum repeat interval for periodic work is 15 minutes.</p><h3>The Importance of Unique Work Requests</h3><p>When scheduling tasks with WorkManager, it’s essential to manage the uniqueness of these tasks to avoid redundant or conflicting work. WorkManager allows you to define unique work using tags or unique work names, which helps in various scenarios:</p><ul><li><strong>Avoiding Redundant Tasks</strong>: By using unique names, you can ensure that the same task isn’t scheduled multiple times, which can save resources and avoid unnecessary processing.</li></ul><pre>WorkManager.getInstance(context).enqueueUniqueWork(<br>    &quot;UniqueWorkName&quot;,<br>    ExistingWorkPolicy.REPLACE,<br>    myWorkRequest<br>)</pre><ul><li><strong>Handling Task Conflicts</strong>: If a task with the same unique name is already scheduled, you can decide whether to keep the existing task, replace it, or append the new task.</li><li><strong>Tracking and Managing Tasks</strong>: Unique names make it easier to track and manage tasks, especially when you need to update or cancel specific tasks.</li></ul><h3>Working with Constraints</h3><p>Constraints in WorkManager allow you to specify conditions that must be met for a task to run. This ensures that tasks are only executed when appropriate, conserving resources and ensuring optimal performance.</p><ul><li><strong>Network Constraints</strong>: Ensure the task runs only when there is an internet connection.</li></ul><pre>val networkConstraints = Constraints.Builder()<br>    .setRequiredNetworkType(NetworkType.CONNECTED)<br>    .build()</pre><ul><li><strong>Battery Constraints</strong>: Specify that the task should only run when the device is charging or has a sufficient battery level.</li></ul><pre>val batteryConstraints = Constraints.Builder()<br>    .setRequiresCharging(true)<br>    .build()</pre><ul><li><strong>Storage Constraints</strong>: Ensure the task only runs if the device has adequate storage available.</li></ul><pre>val storageConstraints = Constraints.Builder()<br>    .setRequiresStorageNotLow(true)<br>    .build()</pre><ul><li><strong>Combination of Constraints</strong>: You can combine multiple constraints to create a comprehensive set of conditions for your task.</li></ul><pre>val combinedConstraints = Constraints.Builder()<br>    .setRequiredNetworkType(NetworkType.UNMETERED)<br>    .setRequiresCharging(true)<br>    .build()</pre><ul><li><strong>Using Constraints in WorkRequest</strong>: Apply the constraints to your WorkRequest to ensure they are respected.</li></ul><pre>val constrainedWorkRequest = OneTimeWorkRequestBuilder&lt;MyWorker&gt;()<br>    .setConstraints(combinedConstraints)<br>    .build()<br><br>WorkManager.getInstance(context).enqueue(constrainedWorkRequest)</pre><h3>Observing WorkManager Tasks</h3><p>WorkManager provides mechanisms to observe the status of your tasks. This allows you to react to changes in task status and update your UI accordingly.</p><ul><li><strong>Observing Task Status</strong>: Use WorkManager to observe the status of a specific work request.</li></ul><pre>WorkManager.getInstance(context).getWorkInfoByIdLiveData(myWorkRequest.id)<br>    .observe(lifecycleOwner, Observer { workInfo -&gt;<br>        if (workInfo != null &amp;&amp; workInfo.state.isFinished) {<br>            // Handle the completion of the task<br>            if (workInfo.state == WorkInfo.State.SUCCEEDED) {<br>                // Task succeeded<br>            } else {<br>                // Task failed or was cancelled<br>            }<br>        }<br>    })</pre><ul><li><strong>Observing Unique Work</strong>: You can also observe the status of unique work by name.</li></ul><pre>WorkManager.getInstance(context).getWorkInfosForUniqueWorkLiveData(&quot;UniqueWorkName&quot;)<br>    .observe(lifecycleOwner, Observer { workInfos -&gt;<br>        for (workInfo in workInfos) {<br>            // Handle each workInfo<br>        }<br>    })</pre><ul><li><strong>Reacting to State Changes</strong>: This can be particularly useful for updating the UI based on task progress, success, or failure.</li></ul><h3>Example Scenarios</h3><ul><li>Data Synchronization: Periodically syncing user data with a server.</li><li>Backup and Restore: Backing up or restoring user data in the background.</li><li>Notifications: Sending notifications to users at scheduled times.</li><li>Long-Running Tasks: Executing tasks that require a considerable amount of time to complete.</li></ul><h3>Conclusion</h3><p>WorkManager is a robust and flexible tool for managing background tasks in Android applications. Its reliability, ability to define tasks with specific constraints, and extensive API support make it suitable for a wide range of use cases. Whether you need to synchronize data, send notifications, or perform long-running operations, WorkManager has you covered. By leveraging unique work requests, observing task status, and utilizing constraints, you can ensure your tasks run efficiently and only under the appropriate conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdb9f2b9f90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>