<?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 Stancho Stanchev on Medium]]></title>
        <description><![CDATA[Stories by Stancho Stanchev on Medium]]></description>
        <link>https://medium.com/@stanchoz3?source=rss-146ac57c1948------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Stancho Stanchev on Medium</title>
            <link>https://medium.com/@stanchoz3?source=rss-146ac57c1948------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:48:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stanchoz3/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[Build an AI Agent on Android with JetBrains Koog]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@stanchoz3/build-an-ai-agent-on-android-with-jetbrains-koog-a9a254dd9069?source=rss-146ac57c1948------2"><img src="https://cdn-images-1.medium.com/max/2600/0*geyjwDOR9sxaWVGh" width="4803"></a></p><p class="medium-feed-snippet">A chat app that calls real tools, with an agent that fits in about 60 lines of Kotlin.</p><p class="medium-feed-link"><a href="https://medium.com/@stanchoz3/build-an-ai-agent-on-android-with-jetbrains-koog-a9a254dd9069?source=rss-146ac57c1948------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@stanchoz3/build-an-ai-agent-on-android-with-jetbrains-koog-a9a254dd9069?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9a254dd9069</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 18:16:22 GMT</pubDate>
            <atom:updated>2026-11-02T18:16:22.918Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Confirmation Bias in AI-Generated Code?]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@stanchoz3/confirmation-bias-in-ai-generated-code-0fa0c5289aff?source=rss-146ac57c1948------2"><img src="https://cdn-images-1.medium.com/max/2600/0*s27ojSXQnyYcuw1u" width="5184"></a></p><p class="medium-feed-snippet">&#x2026;it arrives through a different door than you&#x2019;d expect</p><p class="medium-feed-link"><a href="https://medium.com/@stanchoz3/confirmation-bias-in-ai-generated-code-0fa0c5289aff?source=rss-146ac57c1948------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@stanchoz3/confirmation-bias-in-ai-generated-code-0fa0c5289aff?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fa0c5289aff</guid>
            <category><![CDATA[cognitive-psychology]]></category>
            <category><![CDATA[cognitive-bias]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 15:48:06 GMT</pubDate>
            <atom:updated>2026-08-12T15:48:06.343Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Knowledge Graph search — teaching a tiny on-device chatbot to answer questions that need two facts…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@stanchoz3/knowledge-graph-search-teaching-a-tiny-on-device-chatbot-to-answer-questions-that-need-two-facts-0106ef75e614?source=rss-146ac57c1948------2"><img src="https://cdn-images-1.medium.com/max/2600/0*lkwaNxS6icETkaj4" width="4688"></a></p><p class="medium-feed-snippet">BM25 keyword search can rank documents beautifully and still be structurally incapable of answering &#x201C;who ruled when Bulgaria was founded.&#x201D;&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@stanchoz3/knowledge-graph-search-teaching-a-tiny-on-device-chatbot-to-answer-questions-that-need-two-facts-0106ef75e614?source=rss-146ac57c1948------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@stanchoz3/knowledge-graph-search-teaching-a-tiny-on-device-chatbot-to-answer-questions-that-need-two-facts-0106ef75e614?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/0106ef75e614</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 06:52:47 GMT</pubDate>
            <atom:updated>2026-07-30T06:52:47.082Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[I tried few embedding algorithms for search, then classical BM25 beat every single one of them]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@stanchoz3/i-tried-few-embedding-algorithms-for-search-then-classical-bm25-beat-every-single-one-of-them-43138685c607?source=rss-146ac57c1948------2"><img src="https://cdn-images-1.medium.com/max/2600/0*2CFMMrfRmGcM9nxV" width="4608"></a></p><p class="medium-feed-snippet">A &#x201C;boring&#x201D; 1980s ranking algorithm outperformed six different embedding models on a tiny, structured corpus &#x2014; and why the reason has&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@stanchoz3/i-tried-few-embedding-algorithms-for-search-then-classical-bm25-beat-every-single-one-of-them-43138685c607?source=rss-146ac57c1948------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@stanchoz3/i-tried-few-embedding-algorithms-for-search-then-classical-bm25-beat-every-single-one-of-them-43138685c607?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/43138685c607</guid>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm-applications]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 12:43:36 GMT</pubDate>
            <atom:updated>2026-07-26T12:43:36.456Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Fine-Tuning Qwen3–4B vs. SmolLM3–3B on the Same Math Reasoning Recipe]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@stanchoz3/fine-tuning-qwen3-4b-vs-smollm3-3b-on-the-same-math-reasoning-recipe-9fad07957de3?source=rss-146ac57c1948------2"><img src="https://cdn-images-1.medium.com/max/2600/0*m0hETYuphBsrKtcb" width="7068"></a></p><p class="medium-feed-snippet">Setup. Both models were fine-tuned with an identical pipeline: QLoRA (rank 32, alpha 32) on unsloth/OpenMathReasoning-mini, a 50-step&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@stanchoz3/fine-tuning-qwen3-4b-vs-smollm3-3b-on-the-same-math-reasoning-recipe-9fad07957de3?source=rss-146ac57c1948------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@stanchoz3/fine-tuning-qwen3-4b-vs-smollm3-3b-on-the-same-math-reasoning-recipe-9fad07957de3?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fad07957de3</guid>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 10:43:02 GMT</pubDate>
            <atom:updated>2026-07-21T10:43:02.953Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Retrying Kotlin coroutines with resilience4j in Android]]></title>
            <link>https://medium.com/@stanchoz3/retrying-kotlin-coroutines-with-resilience4j-in-android-6f4146b78b80?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f4146b78b80</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[proandroiddev]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 11:45:39 GMT</pubDate>
            <atom:updated>2024-09-22T11:45:39.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*urrHrHmpzPEIF-o8" /><figcaption>Photo by <a href="https://unsplash.com/@faithgiant?utm_source=medium&amp;utm_medium=referral">Alex Shute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Theory:</strong></h3><p>The reactive parading is very handy in today’s mobile app development. Nevertheless there are situations in which we have to stick to polling approach — just because there is no right callback that to be called to trigger reactiveness, or place of execution of a callback is not right, or we just want to repeat some operation until we get the right result according to some given criteria.</p><p>Polling paradigm requires repetitively execution of one and the same code while we get the desired result. A lot of real example in this regard — calling server API that could be unreachable, geting result from Javascript function executed in Android WebView which is notorious with not calling callbacks on right time so to get correct rendered page information, etc.</p><p>In these cases we need polling to solve issues with too early calling of callbacks ( Android WebView ), or not calling them at all for given period of time (server API). Implementation of polling requires some kind of repetitive calling of one and same code until we get the desired result.</p><p>In Kotlin there are different ways to implement repetitive call of code — retry operator for flows for example just to mention one. There are others also. There are also a libraries dedicated to this taks. I will give an example using the resilence4j library in Android: <a href="https://github.com/resilience4j/resilience4j">https://github.com/resilience4j/resilience4j</a></p><h3><strong>Context:</strong></h3><p>The example which I am presenting here is from real project, which needs to get information for rendered HTML document in android WebView. As android WebView is very dynamic component, a lot of parameters of web document like content width is very difficult to be captured — the developer has to wait full page rendering to finish, so the values returned by Javascript functions in WebView to be corrent. This is nice, but actually we do not have a good enough WebView callback that to mark when full rendering is finished and we can safely to have content width value correct. What we can do — we can write a Javascript function that can try to fix this issue, and we can use a resilience4j to perform repetitive calls to this Javascript function until it gets correct result. Let see a piece of code:</p><h3><strong>Solution</strong>:</h3><pre>@SuppressLint(&quot;SuspiciousIndentation&quot;)<br>fun JavascriptHandler.pointFromTextAsFlowWithRetry(webView: WebView, <br>                                              text:String) = callbackFlow{<br><br>    var point: Point? = null<br>    val javascript = String.format(&quot;PointForText(&#39;%s&#39;)&quot;, <br>                                        String(text.toCharArray()))<br><br>    Retry.of(&quot;retry3&quot;, RetryConfig&lt;Int&gt; {<br>        maxAttempts(3)<br>        failAfterMaxAttempts(true)<br>        retryOnResult {<br>            /*<br>                   IMPORTANT-if this check is missing, <br>                    the flow will be retried 3 times<br>                    even when no exception is thrown in <br>                    executeFunctionSuspend<br>            */<br>            if( it &gt;= 0 ) {<br>                // do not retry when executeFunctionSuspend finished ok - <br>                // if point.x &gt;= 0<br>                false<br>            } else {<br>                // retry if point.x &lt; 0<br>                true<br>            }<br>        }<br>        waitDuration(Duration.ofMillis(200))<br>        retryExceptions(Throwable::class.java, Exception::class.java)<br>    }).executeSuspendFunction {<br>        val response = webView.evaluateJavaScriptSuspend(javascript)<br>        if (response != &quot;&quot;) {<br>            point = Utils.pointFromString(response)<br>            Timber.e(&quot;calculated point x is: &quot; + point!!.x)<br>            Timber.e(&quot;calculated point y is: &quot; + point!!.y)<br>            if (point!!.x &lt; 0) {<br>                throw Exception(&quot;point.x &lt; 0&quot;)<br>            }else {<br>                trySend(point)<br>            }<br>        }<br>        point!!.x // this is the result, checked in retryOnResult {<br>    }<br><br>    awaitClose()<br>}</pre><p>and function webView.evaluateJavaScriptSuspend(javascript) looks like:</p><pre>    suspend fun WebView.evaluateJavaScriptSuspend(script:String):String{<br>        return suspendCoroutine { continuation -&gt;<br>            this.evaluateJavascript(script, ValueCallback { result -&gt;<br>                continuation.resume(result)<br>            })<br>        }<br>    }</pre><p>in function JavascriptHandler.pointFromTextAsFlowWithRetry, I am using Retry.of function, which is resilience4j builder of repetitive structure that will reexecite the code in the block of “executeSuspendFunction”.</p><p>Retry.of has few parameters — first is the name of retry — here I choose “retry3”, the second parameter is of type RetryConfig&lt;Int&gt;, which states building of Retry configuration for return type of Int, which is type returned by the block “executeSuspendFunction”. In this configuration, I give maximum number of repeats as “maxAttempts(3)” which means 3 repetitions — important left only this parameter will make 3 repetitions no matter the function in “executeSuspendFunction” will fail or no — this is very important.</p><p>To make these 3 repetition to happen only in the case of Exceptions — I have to put “retryOnResult” clause and to check there for the correctness of the result. The comment in the code explains the rest according to “retryOnResult”.</p><p>The clause “withDuration” specifies the duration between execution of “executeSuspendFunction” . Here I accept that in the period of 2 x “withDuration” ( 2 here means maxAttempts — 1 ), I will get the correct result from javascript call. The clause “retryExceptions” describes which exceptios will trigger repetition — the fragment:</p><pre>if (point!!.x &lt; 0) {<br>                throw Exception(&quot;point.x &lt; 0&quot;)<br>            }else {<br>                trySend(point)<br>            }</pre><p>explains how to deal with exceptions to trigger repetition. The clause “failAfterMaxAttempts(true)” makes this construct to pass Exception upwards and thus cause crash in the application if there is no desired result achieved after “maxAttepts” number of calls.</p><h3><strong>Usage:</strong></h3><p>Calling JavascriptHandler.pointFromTextAsFlowWithRetry is trivial:</p><pre> javascriptHandler!!.pointFromTextAsFlowWithRetry(<br>                this@aWebView,<br>                text<br>            ).collect { pointReturned -&gt;<br>              <br>            }</pre><h3><strong>Summary:</strong></h3><p>This construct is not simple. But… once written as extension function, it’s usage is simple and well parametrized for different use cases… And works very, very well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f4146b78b80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose — causing Recomposition when changing property value in user defined class]]></title>
            <link>https://medium.com/@stanchoz3/jetpack-compose-causing-recomposition-when-changing-property-value-in-user-defined-class-4c4c41fc4d5c?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c4c41fc4d5c</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 09:56:25 GMT</pubDate>
            <atom:updated>2024-09-14T09:56:25.621Z</atom:updated>
            <content:encoded><![CDATA[<h3>Jetpack Compose — causing Recomposition when changing property value in user defined class</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EtVVirxbp77O1V7g" /><figcaption>Photo by <a href="https://unsplash.com/@wengenroad?utm_source=medium&amp;utm_medium=referral">s w</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here is the thing — user defined classes — especially heavy one — with lot of properties, are not well suited to use in Jetpack Compose. When I am displaying value properties of such class in Compose and user changes some property value, to display the change, recomposition has to happen, but… Recomposition to happen with user defined classes, there are two approaches — both of which are very cumbersome and unhandy — the first approach is when user changes a property a new instance of a user defined class to be created, which will cause recomposition, but with heavy ( not data ) classes this is unpractical — not to say that is not always possible. The second approach is to wrap in MutableState every property which value change has to cause recomposition — ok, but when there are a lot of properties that has to cause recomposition this is more than just boiler plate code — this is very ugly and leads development to slow down. The third approach — changing the policy of MutableState does not work at all with user defined classes and changing their properties.</p><p>So what to do then — for legacy Android applications which does not use data classes, how to make them so changing the value of a property to cause recomposition, so the new value to be displayed ?</p><p>The idea that I am exploiting is to use a variant of remember function that accepts a key as a parameter and every time when the key is changed, recomposition will be called:</p><pre>@Composable<br>inline fun &lt;T&gt; remember(<br>    key1: Any?,<br>    crossinline calculation: @DisallowComposableCalls () -&gt; T<br>): T {<br>    return currentComposer.cache(currentComposer.changed(key1), calculation)<br>}</pre><p>Let me guide you through the whole process. The code looks like this:</p><p>next code is globally defined:</p><pre>class UserDefinedClass{<br>    var name = &quot;&quot;<br>    var age = 31<br>}<br><br>var userDefinedClassInstance = UserDefinedClass()<br></pre><p>this is pretty clear — here I define my class and create an instance, which I will use.</p><p>and in @Composable function:</p><pre>val recomposeKey = remember{ mutableStateOf(userDefinedClassInstance.hashCode()) }<br>val utc = remember(key1 = recomposeKey.value) {  userDefinedClassInstance }<br><br><br><br><br>        Text(text = userDefinedClassInstance.age.toString())<br>        Button(onClick = {<br>                // change value of a property<br>                userDefinedClassInstance.age = userDefinedClassInstance.age + 1<br>                // cause recomposition<br>                recomposeKey.value = userDefinedClassInstance.age.hasCode()<br>            <br>        }) {<br>            Text(&quot;change&quot;)<br>        }</pre><p>note that variable named “utc” is never used, but if you comment it’s declaration, recomposition will stop to happen. Of course I can make change and I can start use the “utc” variable in Text and Button instead of userDefinedClassInstance, but I stick to use userDefinedClassInstance to better show what causes recomposition. The nice ting here is that the developer can work with userDefinedClassInstance, instead with “utc”, which makes code much clearer and easy to deal with.</p><p>When we change the value of recomposeKey, the “utc” will discover that and will causse recomposition, which will display the new value of userDefinedClassInstance.age.</p><p>As “utc” is never used, I can remove it and code becomes:</p><pre>val recomposeKey = remember{ mutableStateOf(userDefinedClassInstance.hashCode()) }<br>remember(key1 = recomposeKey.value) {  userDefinedClassInstance }<br><br>        Text(text = userDefinedClassInstance.age.toString())<br>        Button(onClick = {<br>                // change value of a property<br>                userDefinedClassInstance.age = userDefinedClassInstance.age + 1<br>                // cause recomposition<br>                recomposeKey.value = userDefinedClassInstance.age.hasCode()<br>            <br>        }) {<br>            Text(&quot;change&quot;)<br>        }</pre><p>This is the idea. Hope it will be of good use to all that are in such a need.</p><p>This is ok, but things can be formalized even more. I created a function:</p><pre>fun recompositionGenerator(userDefinedClassInstance:Any,recompositionKey:MutableState&lt;Any&gt;? = null, changeRoutine:(() -&gt; Any)? = null) = sequence&lt;Any&gt; {<br><br>    yield( mutableStateOf(userDefinedClassInstance.hashCode()) )<br>    yield( userDefinedClassInstance )<br>    yield(<br>        if (recompositionKey != null &amp;&amp; changeRoutine != null) {<br>                recompositionKey.value = changeRoutine().hashCode()<br>        } else {<br>                // do nothing<br>        }<br>    )<br><br>}</pre><p>which actually generates the steps of this process. and using this function, I can write the code above like this:</p><p>in @Composable :</p><pre> val recomposeKey = remember{<br>        // taking first step of the process<br>        recompositionGenerator(userDefinedClassInstance).first() <br>                                    as MutableState&lt;Any&gt; }<br>    remember(key1 = recomposeKey.value) {<br>        // taking second step of the process<br>        recompositionGenerator(userDefinedClassInstance).drop(1).first() <br>                                    as UserDefinedClass }<br><br><br>        Text(text = userDefinedClassInstance.age.toString())<br>        Button(onClick = {<br>            // taking 3-rd step of the process<br>            recompositionGenerator(userDefinedClassInstance,recomposeKey ){<br>                userDefinedClassInstance.age = userDefinedClassInstance.age + 1<br>                userDefinedClassInstance.age<br>            }.drop(2).first()</pre><p>Thi sis more formal, although it is more code, but it is easier to determine where which step is used and function recompositionGenerator is reausable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c4c41fc4d5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin — waiting for coroutine result while iterating a collection]]></title>
            <link>https://medium.com/@stanchoz3/kotlin-waiting-for-coroutine-result-while-iterating-a-collection-c813aff6932e?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/c813aff6932e</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Sun, 03 Mar 2024 16:21:02 GMT</pubDate>
            <atom:updated>2024-03-03T16:21:02.450Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kotlin — waiting for coroutine result while iterating a collection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*li9lXiVgLUvE3ZLv" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=medium&amp;utm_medium=referral">Susan Q Yin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What is this about… Imagine the situation in which you have to download a lot of files on the device. You know the urls of these files. How one has to proceed ?</p><p>Let we turn these requirements in developer task:</p><p>Download of a single file has to be made out of Main thread — in Kotlin usually we are using suspend function on Dispatchers.IO</p><p>Do not forget that Dispatchers.IO is limited to 64 threads and is combined in one pool with Dispatchers.Default — which gives us even less than 64 threads of IO</p><p>I want to have a control over the number of simultaneous downloads — in this situation I want to run downloads sequentially — one by one. ( I can run every next download request in the callback when one request is finished, but this makes the structure of code too messy. Also another solution to this task is to use Dispatcher.IO.limitedParallelism and it will solve this issue, but I will have less control with this solution). So let focus now on the task:</p><p>Download files URLs are organized in collection.</p><p>Solving this task requires iterating through the collection of file URLs and starting a function for downloading a file, which has to be suspend function, and as I want to download single file ( not multiple files ) simultaneously, the collection iterating loop has to wait currently started suspend function to finish.</p><p>Take into account, that if I not restrict the number of simultaneous downloads, I can get into Dispatchers.IO flooding, starting a lot of coroutines simultaneously, which taking into account that Dispatchers.IO and Dispatchers.Default share a common thread pool of 64 threads, could lead to slowing of Android application.</p><p>This is the reason because I don’t want just to iterate through the URL collection and start downloading coroutines without waiting them to finish.</p><p>Using WorkManager and leaving it to manage itself let say 120 single tasks does not give good results. I checked this solution and it reflects to UI, making it show and unresponsive.</p><p>Again I can use Dispatcher.IO.limitedParallelism and it will solve this issue, but I will have less control over download with this — for example when few physical files form one logical entity ( audiobook chapter ( which is logical entity ) is formed by few mp3 files, if I run parallel downloads, I will have difficulties to display download progress ).</p><p>This is the formulation of the task.</p><p>I propose here a one solution, based on CountDownLatch class. There are enough information about this class and examples for it’s usage, so here I am going straight to solution of our task:</p><pre>fun &lt;T&gt; Collection&lt;T&gt;.forEachAsync(<br>  scope: CoroutineScope = CoroutineScope(Dispatchers.IO)<br>                              , asyncFun:suspend (T, () -&gt; Unit) -&gt; Unit){<br>    var index = 0<br>    while (index &lt; size){<br>        val cdl = CountDownLatch(1)<br>        val element = this.elementAt(index)<br>        scope.launch {<br>            asyncFun(element){<br>                cdl.countDown()<br>            }<br>        }<br>        cdl.await(1, TimeUnit.MINUTES)<br>        index++<br>    }<br>}</pre><p>The solution is presented as an extension function of Collection interface.</p><p>The code is pretty straight forward — I am starting collection iteration loop with creating a CountDownLatch with counter equal to 1. This is a “while” loop that uses counting variable, named “index”. Just at the end of the loop, I make increasing of this variable possible after ContDownLatch ( variable cdl ) is counted to zero, which happens in the callback of the “asyncFun”.</p><pre>val executionTasks:List&lt;OneTimeWorkRequest&gt;<br>    executionTasks = bookListBuilder()<br>...<br>     executionTasks.forEachAsync(CoroutineScope(Dispatchers.IO)<br>                            ){ task,  countDownLatchCountDown -&gt;<br><br>                WorkManager.getInstance(BookshelfApp.getAppContext())<br>                            .enqueue(task)<br>                // callback for every OneTimeWorkRequest<br>                WorkManager.getInstance(BookshelfApp.getAppContext())<br>                    .getWorkInfoByIdLiveData(task.id)<br>                    .asFlow().onEach { workInfo -&gt;<br>                        if (workInfo.state == WorkInfo.State.ENQUEUED) {<br>                            Timber.d(&quot;LiveData changed:...ENQUEUED&quot;)<br>                        } else if (workInfo.state == WorkInfo.State.SUCCEEDED) {<br>                            Timber.d(&quot;LiveData changed:...SUCCEEDED&quot;)<br>                            Timber.d(<br>                                &quot;LiveData changed:...%s&quot;,<br>                                workInfo.outputData.keyValueMap[KEY_SUCCESS_INFO_DOWNLOAD_TITLE].toString()<br>                            )<br>                            // do not miss this !!!<br>                            countDownLatchCountDown.invoke()<br>                        }else if (workInfo.state == WorkInfo.State.FAILED){<br>                            // do not miss this !!!<br>                            countDownLatchCountDown.invoke()<br>                        }<br>                    }.collect()<br><br>            }</pre><p>The usage is shown in the code above. It is also straight forward. This example is little complicated, as it uses WorkManager, but in general, the idea is clear. It is important to mention not to forget “countDownLatchCountDown.invoke()” in the callback, otherwise, the loop itself will wait a minute, before start next iteration.</p><p>This is one way to solve this tough task. There other ways also… for them — in some next article.</p><p>Thank you for your time !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c813aff6932e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin coroutines inconvenience…]]></title>
            <link>https://medium.com/@stanchoz3/kotlin-coroutines-inconvenience-42ca85b30726?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/42ca85b30726</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[completablefuture]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 13:59:25 GMT</pubDate>
            <atom:updated>2024-02-20T13:59:25.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ME75xUJoT2F_hqU_" /><figcaption>Photo by <a href="https://unsplash.com/@szvmanski?utm_source=medium&amp;utm_medium=referral">pawel szvmanski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Coroutines are nice…Mostly… except, there are cases in which they are extremely inconvenient. One such case is when a non-suspending function returns result, that depend from the result, returned by suspend function. Not too many such cases… may be one will say. Let me not agree with such opinion — there are a lot of libraries ( both Google and 3-rd party ) which classes has methods that have to be overridden, and which are non-suspending return values functions — there are such function in Android Services, Android media3 media player, etc.. In such a functions it becomes extremely difficult to call and wait for results from Room database for example, because database access functions has to be executed in non-blocking way and developers usually use suspending functions, but calling functions are not suspending. So we get into trouble with coroutines even in this very common scenario. As you already know uses of runBlocking is highly discouraged by Google.</p><p>There are few solutions of this issue. Unfortunately none of them is under the umbrella of coroutines library, which make this library somehow difficult to communicate with external world of result returning overrides.</p><p>One such solution is to borrow from Java the CallableFuture class. This class actually is pretty old — it was introduced in Java 8. In this regard, actually it turns out that Java has pretty good and modern multi-threading primitives, most of which unfortunately failed to get in the main stream Java programming, leaving the wrong impression that Java relays totally on old-fashioned Thread class.</p><p>I will not delve here in deeps of the CompletableFuture class — there is pretty good amount of documentation and examples, but I want to point out that this class is nice replacement of coroutines when we need to call and get result from async code.</p><p>Here is code that I am using in Android</p><pre>fun &lt;AP, AR, TAR&gt; withCompletableFutureDoAsyncAndGetResult(doAsyncParameter:AP<br>                                , doAsync:(AP) -&gt; AR<br>                                , handleDoAsyncResult:(AR?)-&gt;TAR?):TAR?{<br>    var returnResult:TAR? = null<br>    CompletableFuture.supplyAsync{<br>        doAsync(doAsyncParameter)<br>    }.handle { doAsyncResult, u -&gt;<br>        if( u != null ){<br>            u.printStackTrace()<br>            null<br>        }else{<br>            doAsyncResult<br>        }<br>    }.thenAccept {<br>        returnResult = handleDoAsyncResult(it)<br>    }.join()<br>    return returnResult<br>}</pre><p>As it is easily visible — this function is non-suspending — it can be called outside of coroutine, execute async code in doAsync function, giving it the parameter doAsyncParameter, can do some handling of doAsync return result via handleDoAsyncResult and return result of it’s execution back to calling function.</p><p>Calling of this function from override can look like this:</p><pre> override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {<br><br>          val audioFiles:List&lt;DBAudioFiles&gt;? =<br>          withCompletableFutureDoAsyncAndGetResult&lt;Int, List&lt;DBAudioFiles&gt;?<br>                                                    , List&lt;DBAudioFiles&gt;?&gt;(<br>                  doAsyncParameter = <br>                  selectedManifestListItem!!.getManifestItem().id<br>                  , doAsync = {<br>                      DBAudioFiles.getAllFilesForManifestNonSuspend(it)<br>                  }<br>                  , handleDoAsyncResult = {<br>                              it?.let {<br>                                  // simple - do nothing, but you can if you wish<br>                                  it<br>                              }<br>                  }<br>          )<br><br>  seekInfoRepository.buildSeekInfoForDisplayingContext(audioFiles!!)<br><br>...<br> return Service.START_STICKY<br>}</pre><p>Here audioFiles, which are result of calling of withCompletableFutureDoAsyncAndGetResult function is used in seekInfoRepository.buildSeekInfoForDisplayingContext.</p><p>In such a case, the developer is blocked — you see — it is an override, so we can not change the signature of the function, as we cannot change the architecture of the library, so it to be friendly to coroutines.</p><p>Hope this idea will help in our pursuit for flexible and maintanable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42ca85b30726" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Markov chain for my recruitment process]]></title>
            <link>https://medium.com/@stanchoz3/markov-chain-for-my-recruitment-process-727aaeb8594f?source=rss-146ac57c1948------2</link>
            <guid isPermaLink="false">https://medium.com/p/727aaeb8594f</guid>
            <category><![CDATA[hiring]]></category>
            <category><![CDATA[discrete-markov-chain]]></category>
            <category><![CDATA[human-resources]]></category>
            <category><![CDATA[people-analytics]]></category>
            <category><![CDATA[markov-chains]]></category>
            <dc:creator><![CDATA[Stancho Stanchev]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 13:36:56 GMT</pubDate>
            <atom:updated>2023-04-06T13:37:45.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpD9SnnXxfUGBXKe" /><figcaption>Photo by <a href="https://unsplash.com/@karsten116?utm_source=medium&amp;utm_medium=referral">Karsten Winegeart</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A wise man once said: there are only three types of information in a human conversation — models, data, and… non-sense. Models give us an <em>actionable</em> understanding for things, objects and processes. Actionable is important word here and we have to make distinction between theory and modeling — theories gives us a theoretical knowledge… which is not always actionable. That is importance of models — we are using them for deciding what actions to take… and when. Markov chains are very wide used stochastic modeling tool for decision making. There are different classifications of Markov chains — I will not get deep into this here, just will state one important differentiation — discrete time Markov chains and continuous time Markov chains. Markov chain consist of set of states and set of transitions between states. These processes can be depicted as a directed graph. The model in this article is a discrete Markov chain — and I am taking “technical interviews” as time discretions in this model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*f9MOzx2kkuLefaGM5hYvqw.png" /></figure><p>This graph describes a process with two states — “Not Hired” and “Hired”.Every state depicts an end result of a given technical interview that I had with a candidate for position of QA in my team. There is a transitions between all states. These transitions are show with arrows between start and end state. On every arrow, the probability of this transition to happen is shown ( for example the probability this process to end in “Hired” state, starting from “Not Hired” state is 3 / 8 )</p><p>And as every graph, this can be presented as a matrix with states in rows and columns, and with probabilities for transitions between states as values. For Markov chain, sum of probabilities by row has to equal to 1, but this is not mandatory for sum of probabilities by column ( on graph representation — sum of all outgoing arrows from a state has to equals to 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*wz4RvuXw-Tw6mcFwT_5urQ.png" /></figure><p>States of the process always needs some explanation. In his process there are two states — “Not Hired” — when hiring process finishes without hiring, and “Hired” when process finishes with hiring of the candidate.</p><p>My story is as follows: For a time period of 4 years, I had a total of 8 interviews for hiring a QA for my team. Of which I hired 3 people ( that is depicted in green cell with value 3 / 8 ), and rejected 5 people ( blue cell with value 5 / 8 ). From 3 hired people 2 already left the company ( red cell with value 2 / 3 ), and one stays, and still works with us ( pink cell with value 1 / 3 ).</p><p>How can this model help in hiring process? Well… it can answer a very important question:</p><ol><li>how many candidates I have to interview, so there to be chance this process to finish in “Hire” state? ( stated other way — to hire a QA )</li></ol><p>Markov chains theory describes a thing called “stationary probabilities” — these are probabilities - that a process to be in a given state, when the process is run endlessly. For the process depicted here, it is as follows:</p><blockquote>Not Hired (stationary) = red cell / ( red cell + green cell )</blockquote><blockquote>Hired ( stationary ) = green cell / ( red cell + green cell )</blockquote><p>Which calculated is :</p><blockquote>Not Hired ( stationary ) = 0.63999</blockquote><blockquote>Hired ( stationary ) = 0.35999</blockquote><p>So my interview process has a probability for hiring of 36%. Which means that my criteria for hiring are relatively relaxed, statistically speaking. If I get the reciprocal value</p><blockquote>1 / Hired ( stationary )</blockquote><p>it will give me the number of interviews that I have to complete so to have a chance to hire. In my case it is 2.77. I’ll take it as 3 for practical use. So statistically, I have to have interviews with 3 different candidates, so there to be a chance I to hire. Or said another way — the HR team has to supply me with 3 candidates for technical interview, before there is a real chance for hiring.</p><blockquote>This is good to know…</blockquote><p>because now I can help the HR team to plan better their candidate searching efforts and candidates relations.</p><p>For example they can do an intensive search until they find 3 candidates for the QA position, after which they can relax searching as there is a great chance that the process will finish in “Hire” state. If the process does not finish in “Hire” state, HR team could start again intensive search for next 3 candidates… but other strategies are possible as well.</p><p>Models make numbers to speak.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=727aaeb8594f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>