<?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 Jakub Tapuć on Medium]]></title>
        <description><![CDATA[Stories by Jakub Tapuć on Medium]]></description>
        <link>https://medium.com/@jakob.mats?source=rss-bcfcf82cb217------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WGf28oNFYSeV8JML98C_aQ.jpeg</url>
            <title>Stories by Jakub Tapuć on Medium</title>
            <link>https://medium.com/@jakob.mats?source=rss-bcfcf82cb217------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:31:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jakob.mats/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[Your monad tutorial sucks]]></title>
            <link>https://medium.com/@jakob.mats/your-monad-tutorial-sucks-4d9795881995?source=rss-bcfcf82cb217------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9795881995</guid>
            <category><![CDATA[monads]]></category>
            <category><![CDATA[purescript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[haskell]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jakub Tapuć]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 17:01:28 GMT</pubDate>
            <atom:updated>2022-07-25T17:01:28.318Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve tried picking up a purely functional language quite a few times and every time I did, I kind of knew that resorting to reading another monad tutorial was a terrible idea. So I only did so for my own amusement to find them more and more aggravating with every year that passed (yes, that many times).</p><p>The rule of thumb is: the more exalted and rejoiced the author seems to be in explaining what a monad is, the more certain you can be it’s going to be completely off the mark and ridiculous. So, why another rant on how monad tutorials suck? Well, if they can write them, why can’t I comment on how bad they are?</p><p>You will not see me writing what monads, functors or applicatives are. Why? Because after having spent a good month trying to comprehend them, I do confess that my understanding is still lacking. For some, that’d be a terrific moment to write another <em>great</em> tutorial. Ultimately though, no one interested in learning what they are will gain anything from reading such crappy tutorials. They’ll only get confused. As a reader, go pick a <a href="https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/">good book on category theory</a> and stop getting lured into thinking that monads are easy to understand. They’re not — or at least not initially. We don’t think in categorical terms in our day-to-day life. Category theory is very abstract and purely functional languages operate in somewhat eerie semantics when coupled with CT.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*w8uk2kPpUJ1QPT6Azy3p5g.gif" /></figure><p><a href="https://terbium.io/2020/06/monads/">They’re not a type (sigh)</a>, <a href="https://samgrayson.me/2019-08-06-monads-as-a-programming-pattern">it’s not a design pattern</a> (also, while we’re at it — aren’t Haskell programmers programmers?), <a href="http://kawagner.blogspot.com/2007/02/understanding-monads-for-real.html">they’re not a macro 👁️👄️👁️</a> &amp; <a href="https://elbear.com/how-to-use-monads-without-understanding-them.html">you certainly must understand them in order to use them</a> (what the actual fuck?).</p><p>Are you in a hurry? How the fuck is that possible, there are probably less Haskell job listings in your vicinity than for COBOL. Are you trying to impress people at parties with your knowledge of words like “monad transformers” and “asynchronous effects”? You won’t get laid, I promise you that. Take your time, work through the exercises, take notes, make drawings and hydrate. That’s it.</p><h4>The bitter afterword</h4><p>My language of choice is <a href="https://www.purescript.org/">PureScript</a>. The more I understand it the more I like it. And I realize that little do I know sometimes despite the fact I have a good couple of years of experience in imperative languages. Don’t be ashamed of saying that you don’t understand something — isn’t the rewarding feeling of achievement worth it when all of a sudden everything finally clicks? Don’t let your inner child die just because you want to rush through things or evangelize others on ideas you don’t know the first thing about.</p><p>The best resources for learning PureScript I could find are:</p><ol><li><a href="https://book.purescript.org/">The PureScript book</a></li><li><a href="https://jordanmartinez.github.io/purescript-jordans-reference-site/Preface.html">PureScript: Jordan’s Reference</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9795881995" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is Free Pascal better than PHP?]]></title>
            <link>https://medium.com/swlh/why-is-free-pascal-better-than-php-654d6c569e7b?source=rss-bcfcf82cb217------2</link>
            <guid isPermaLink="false">https://medium.com/p/654d6c569e7b</guid>
            <category><![CDATA[type-systems]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[free-pascal]]></category>
            <dc:creator><![CDATA[Jakub Tapuć]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 18:46:05 GMT</pubDate>
            <atom:updated>2020-05-03T10:15:05.592Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A nonsensical ramble on type systems</strong></h4><h4>Introduction</h4><p>With modern codebases growing at an insanely fast pace we have generally come to terms with the fact that certain traits in our beloved programming languages determine the quality of the end product in one way or another. Be it support for seamless modular programming, static type system or concurrency and parallelism with robust ways of maintaining state in distributed systems.</p><h4>Now and then</h4><p>Yet in some ways (with numerous exceptions of course) we still use the same programming languages as we did twenty or so years ago. Most of them have acquired some new interesting features usually inherited from functional languages derived from the lambda calculus — lambda expressions (so called arrow functions), immutability, referential transparency, list comprehensions; oftentimes structures from category theory have been incorporated as well — algebraic data types (product types also called tuples and sum types often called discriminated unions), functors, applicatives (applicative functors) and monads to name a few. Another thing that cannot be neglected is a common attempt at standardizing languages and their tooling — formal specifications (even PHP got an <em>a posteriori</em> one), linters, tools for auto-formatting the code and building pleasant-looking documentation.</p><h4>A spoon of tar in a barrel of honey</h4><p>However, we have to be honest here. There are languages still in use today that somehow overslept this phase of accelerated growth. And when they woke up it was way too late to catch up. Let’s talk PHP.</p><p>In today’s world where strong static typing is becoming more and more crucial to creating robust, performant and secure applications, it’s probably well-grounded to say that PHP’s type-juggling might not be the best fit. Recent addition of gradual typing is not sufficient considering it still lacks generics. Also, there exist many peculiarities within the type system itself — when talking about generics it’s needless to say that the inability to express object boxing and unboxing is a bit surprising. Now, let’s go back in time a bit, to year 2000 when PHP 3 was still in the game and its successor, PHP 4 was released.</p><h4>The legacy — type juggling</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*TebK20uFNW6rV8fiyp9duA.jpeg" /></figure><p>The old <a href="https://web.archive.org/web/19991128042026/http://www.php.net/manual/language.types.type-juggling.php3">PHP 3 manual</a> explicitly mentions type juggling as a language feature. The not so good thing about type juggling is the mental juggling you need to perform in your head when your script goes astray without throwing any exceptions. Even more interesting is the fact that it’s still <a href="https://www.php.net/manual/en/language.types.type-juggling.php">there</a> in PHP 7.4. This is the easiest way to bypass PHP’s gradual type system since operators are baked into the language and their semantics are exempt from the type system itself. Now let’s see if we can recreate some of the examples from before almost 20 years ago.</p><pre>// 1<br>$foo = &quot;0&quot;;  // $foo is string (ASCII 48)<br>$foo++;      // $foo is the string &quot;1&quot; (ASCII 49)</pre><pre>// 2<br>$foo += 1;   // $foo is now an integer (2)<br>$foo = $foo + 1.3;  // $foo is now a double (3.3)</pre><pre>// 3<br>$foo = 5 + &quot;10 Little Piggies&quot;; // $foo is integer (15)<br>$foo = 5 + &quot;10 Small Pigs&quot;;     // $foo is integer (15)</pre><ol><li>This partially holds true. You can still use the post-increment operator on strings but the variable will be cast into an integer implicitly.</li><li>Implicit integer-float juggling is still pervasive in the language.</li><li>Nowadays it’s invalid to use a malformed integer literal (which can be a string) with arithmetic operators.</li></ol><p>But all of this is so easy to write and natural for us humans to understand. It has a low cognitive load compared to, say, OCaml where arithmetic operators are in fact regular infix functions which aren’t polymorphic over their arguments.</p><pre>(*<br>   These are code samples from an Ocaml REPL session.<br>   The string &#39;utop #&#39; is the prompt.<br>*)</pre><pre>utop # (+);;<br>- : int -&gt; int -&gt; int = &lt;fun&gt;</pre><pre>utop # 1 + 1;;<br>- : int = 2</pre><pre>utop # 1.0 + 1.0;;<br>Error: This expression has type float but an expression was expected of type<br>         int</pre><pre>utop # (+.);;<br>- : float -&gt; float -&gt; float = &lt;fun&gt;</pre><pre>utop # 1.0 +. 1.0;;<br>- : float = 2<br></pre><p>Of course, type promotions like widening or narrowing numeric values are prevalent in many strongly typed programming languages but do not escape the language’s type system as easily as in PHP. Most of the time they need to be signaled explicitly - thus narrowing a long integer to short integer requires an explicit cast. Even then, you cannot just implicitly cast a string to an integer by using an arithmetic operator.</p><p>Also, there is a very clear contrast between strong vs weak typing and static vs dynamic type resolution. It turns out you can get a very cohesive and reasonable strong-dynamic type system based on predictable <a href="https://wiki.c2.com/?RubyCoerce">coercion </a>— Ruby is a good example of such language.</p><p>Talking about strongly typed languages though— ever heard of Object Pascal?</p><h4>P̶u̶n̶k̶ Pascal not dead</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*74LP4KDdFVDUvhOYhyPO4A.png" /><figcaption><a href="https://upload.wikimedia.org/wikipedia/commons/d/df/Turbo_Pascal_7.0_Scrren.png">https://upload.wikimedia.org/wikipedia/commons/d/df/Turbo_Pascal_7.0_Scrren.png</a></figcaption></figure><p>The Pascal family of languages is quite large. Some of its descendants are still actively maintained. Object Pascal for instance was an implementation originally created by Apple. There exists a couple of Object Pascal-flavored languages. One such example is Delphi. It has its mature open-source counterpart — Free Pascal. It’s a very modern implementation supporting modular programming, generics, delegates, function &amp; operator overloading and much more. It has a great <a href="https://www.lazarus-ide.org/">tooling support</a> and a package manager. Free Pascal implements the <a href="https://www.iso.org/standard/13802.html">ISO 7185:1990</a> official Pascal standard.</p><p>Pascal has been a statically and strongly typed language from its inception dating back to 1970s. Its author Niklaus Wirth designed a couple of programming languages but not all of them were statically typed (<em>vide</em> <a href="https://en.wikipedia.org/wiki/Euler_(programming_language)">Euler</a>). This is in contrast to PHP which was designed as a glue language for making static webpages less static.</p><p>What follows is a brief, nonsensical yet entertaining attempt at comparing the type systems of languages that probably should never be compared in any way. In particular, we’re going to take a look why the lack of generics is such a pain in PHP.</p><h4>What exactly are generics</h4><p>Generics is a feature that lets you write code that is parametrized by additional types. The most obvious example of a useful parametrized structure is a collection.</p><h4>Splish-splash</h4><p>PHP has its dedicated collection-like datatype for storing values — arrays. Once something is put inside an array it can be retrieved by its index. There are times though when you’d like to use one of the SPL collections such as SplFixedArray which may prove to be more space efficient than an ordinary array. As with arrays you can put there values of any type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afd81c416381ffab82a5f275129b5fae/href">https://medium.com/media/afd81c416381ffab82a5f275129b5fae/href</a></iframe><pre>PHP Error:  Call to undefined method Dishwasher::bark()</pre><p><em>I have never seen a barking dishwasher but I am no expert in this</em>. We would like to find a way of inserting elements into an array collection in a dog-aware fashion. One way would be to try something like the following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8c87bd10c7690f307b0e3d6a12b7706/href">https://medium.com/media/a8c87bd10c7690f307b0e3d6a12b7706/href</a></iframe><pre>PHP Fatal error:  Declaration of DogFixedArray::offsetSet(int $index, Dog $dog) must be compatible with SplFixedArray::offsetSet($index, $newval)</pre><p>It won’t work. PHP simply forbids that. If a parameter in the base class is not typed then it virtually has no type at all — it’s called “mixed” in PHP. You can’t specify it in child classes because this would mean changing the method signature which is justly prohibited. It’s a bit of a baffling concept since there is no “mixed” type hint so sometimes obvious <a href="https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)">variance rules</a> can’t be realized. There exists an <a href="https://wiki.php.net/rfc/mixed-typehint">RFC</a> for that though.</p><p>One thing that one could resort to would be to use the instanceof operator inside offsetSet. It should be noted however that this operator obtains runtime information, so after all you would need to sacrifice one thing for another — space efficiency versus runtime overhead.</p><h4>Generic collections in Free Pascal</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*c6Rp5ytXPMAtvDb9BiuWZw.gif" /><figcaption>Free Pascal logo</figcaption></figure><p>It’s time to see how Pascal treats generic collections and the obvious implications this treatment has on type safety in the language.</p><p>Free Pascal comes with a rich open-source standard library called RTL (Runtime Library) which contains a unit called FGL¹ (Free Pascal Generic Lists). The following is an example that uses this unit.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/378a50d9428671ee0cc859dce9839903/href">https://medium.com/media/378a50d9428671ee0cc859dce9839903/href</a></iframe><p>Points 1–3 are explained in the code.</p><p>4. The “specialize” keyword is used to create a new instance of a parametrized type. From then on TDogList refers to a collection of objects of type TDog.<br>5. Methods are defined outside of class declarations.<br>6. The “magic” variable Result works a bit like the return keyword found in many mainstream languages. <br>7. Create is the name of an actual constructor.<br>9. It turns out you can even have a foreach loop in Free Pascal.<br>10. Free Pascal doesn’t have a garbage collector so objects need to be freed when done working with.</p><p>It’s not necessary to free the list’s items because by default it holds ownership of its data and frees it when it’s destroyed. It can be controlled by passing False as the first and only parameter to the TFPGObjectList constructor.</p><p>Finally, the eighth point proves that it’s impossible to add an object of class TDishwasher to a list of TDogs.</p><h4>Verbosity</h4><p>Declaring new instances² of generic types in Free Pascal is mandatory³ which is a bit verbose compared to, say C#:</p><pre>var words = new List&lt;string&gt;();</pre><p>In C# type instantiation is <em>ad hoc</em> while in Pascal you need to take care of creating type synonyms beforehand, in the “type” section of a unit file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb0087abc9a107bdb071148ad3734444/href">https://medium.com/media/eb0087abc9a107bdb071148ad3734444/href</a></iframe><h4>Under the hood</h4><p>Internally, Free Pascal’s take at generics is somewhat different to that present in C++or Java. When a unit is compiled a PPU file is generated. It contains meta-information about the unit. Most importantly for us it maintains a token buffer used by the compiler to create specialized implementations based on the generic type definitions. The workflow looks as follows.</p><pre>1. For each generic type:<br>generic TGeneric&lt;T&gt; = ...<br>Create a token buffer inside the PPU file with meta information.</pre><pre>2. For each occurrence of:<br>TSpecialized = specialize TGeneric&lt;*&gt;<br>Parse the specialization and create the conrete type by substituting T for * where * is a simple type</pre><p>At the conceptual level it’s not much different from other languages like Java but the implementation differs significantly. And because the specialization happens at compile time, Free Pascal’s generics are not subject to type erasure as it happens to be in <a href="https://docs.oracle.com/javase/tutorial/java/generics/erasure.html">Java</a>.</p><h4>Summary</h4><p>This article sums up why the lack of generics in PHP is painful and why its lax type system sometimes just doesn’t help with writing good code. Free Pascal’s take on generics was presented and how it simplifies many of the problems that exist even in modern versions of PHP. Type juggling was juxtaposed with coercion in dynamic languages like Ruby. Finally, a full working example in Free Pascal was demonstrated to show how common typing issues can be alleviated with the use of generics.</p><p>[1] From what I know, FGL is not the most comprehensive generic collection library for Free Pascal but there exist more suitable alternatives.<br>[2] By “instance of a generic type” I mean another type that is no longer polymorphic. Strictly speaking, it doesn’t contain any free type parameters.<br>[3] In fact, Pascal supports two main modes {$MODE OBJFPC} and {$MODE DELPHI}. In the Delphi compatibility mode you can skip the ahead-of-time type declarations. Also, the “specialize” keyword must not be used at all.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=654d6c569e7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-is-free-pascal-better-than-php-654d6c569e7b">Why is Free Pascal better than PHP?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RxPHP Schedulers (part 2)]]></title>
            <link>https://medium.com/swlh/understanding-rxphp-schedulers-part-2-6c4d01d7e65e?source=rss-bcfcf82cb217------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c4d01d7e65e</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[Jakub Tapuć]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 21:23:40 GMT</pubDate>
            <atom:updated>2019-10-04T21:25:57.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqiQcWAdyLmUVIZO56Wd8A.png" /><figcaption>It’s time to stop!</figcaption></figure><h3>Introduction</h3><p>In the <a href="https://medium.com/@jakob.mats/understanding-rxphp-schedulers-part-1-d3c0ab6eb881">previous article</a> we discussed how the immediate scheduler works in RxPHP. In this post we are going to cover the virtual time scheduler and then its descendant — the event loop scheduler which opens up a brave new world of asynchronous possibilities to us. Of course, writing code that schedules things asynchronously by hand in PHP would be quite tiresome so we’re gonna use <a href="https://amphp.org/amp/">Amp</a>. I’m purposefully not using ReactPHP as I’m more familiar with Amp and its <em>yield-philosophy</em> just appeals to me much more.</p><h3>Entering the bizarre world of virtual time</h3><p>As mentioned above the two schedulers we’re gonna cover in this post are based on the concept of <em>virtual time</em>. Understanding it is a crucial step towards grasping the event loop scheduler that we’re going to talk about later on.</p><p>So, without further ado let me take you on a journey through time. Remember when we talked about the three main things that make up a scheduler?</p><blockquote>Schedulers know when and where to execute actions.</blockquote><p>We’re going to focus on the when part of this sentence. First of all, it is really important to realize that a virtual time scheduler does not need to deal with real system clock at all. Instead, depending on the implementation it can be initially set to 0. This holds true if it look at <em>VirtualTimeScheduler</em>’s constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efcee4cc1c85b56686e1c660bfba53ea/href">https://medium.com/media/efcee4cc1c85b56686e1c660bfba53ea/href</a></iframe><p>The good thing about schedulers is that we can use them in separation. Let us then look at some real code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ee958a138a4969a1ea3f397cea2217a/href">https://medium.com/media/2ee958a138a4969a1ea3f397cea2217a/href</a></iframe><p>Here, we create a new scheduler instance and pass 0 as the starting time. What is this weird callback though? It’s a <em>comparer</em> function. While useless in the context of the immediate scheduler it is indispensable in the realm of virtual time. The scheduler will use the callback every time it needs to know how two timestamps relate to each other.</p><p>Next, we schedule a hello world callback to be executed later. If we were to leave out the last line no output would have shown up. This is another thing that’s different from the immediate scheduler which was processing actions as soon as they arrived.</p><p>Now you probably remember that with the <strong>immediate</strong> scheduler we weren’t able to <strong>delay</strong> our actions — for obvious reasons, of course. Since the virtual time scheduler can compare two timestamps for us, we can try to kindly ask it to do so. The easiest way is to create an observable with a delay. Think about it — when the action is enqueued the scheduler needs to calculate if the callback is ready to be invoked or not by <em>comparing</em> two timestamps. How about really taking it on another time level and making it fire after 10 minutes?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/057f12adf7a048c93551a6a1e7c6327f/href">https://medium.com/media/057f12adf7a048c93551a6a1e7c6327f/href</a></iframe><p>Let’s run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*lnHsMviOX_bDuU-ngwsTRg.gif" /><figcaption>Wait, what?</figcaption></figure><p>No, I did not accelerate the video. The output is immediate. <em>Wait a second — did I just lie to you again?</em> Well, just a tiny wee bit. Why do we get to see the result right away? Because virtual time is not human time. What for you seems like ten minutes for the virtual time scheduler might just as well take a couple of milliseconds. The next snippet should make it even clearer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63cfc54c78057fc1add0eecb9556d19d/href">https://medium.com/media/63cfc54c78057fc1add0eecb9556d19d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*SXdZyuex8xc6K0i619OeJg.gif" /><figcaption>This is actually lame</figcaption></figure><p>In the code above we created two objects — a simple <em>ReturnObservable </em>and an <em>IntervalObservable</em>. Things are starting to get a little more interesting at this point. On one hand the code was executed immediately once again but on the other the results from the two subscriptions were interleaved just as expected.</p><p>This proves my point exactly.</p><blockquote>Virtual time is not human time.</blockquote><p>The main concern of the virtual time scheduler is to make sure that every action is carried out in a timely fashion but it’s implemented in a way that leaves out the need to schedule work asynchronously. Apart from that, it neglects the absolute time values —it only cares about temporal relations, that is what comes before and what comes after. <em>VirtualTimeScheduler</em> is a fusion between the immediate and event loop schedulers— it supports delaying, interval observables and other ReactiveX goodies, however it’s synchronous by design. In fact, the event loop scheduler is based off of it and simply adds the missing async layer.</p><h3>When the async kicks in</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujwRpU19dL74jJnHql-gnQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bill_oxford?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Bill Oxford</a> on <a href="https://unsplash.com/s/photos/cogwheel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The real journey begins now. It’s time we met the event loop scheduler. Up until now we’ve only dealt with synchronous code. The difference between the virtual time scheduler and the event loop scheduler is actually quite subtle. As we already know there is an inheritance relation between the two and most of the functionality is basically the same with respect to enqueuing actions and then dequeuing them to invoke them when the time comes. But the event loop scheduler is capable of receiving an action and forwarding it to the actual event loop. It’s like two gears — a smaller one (scheduler) and a bigger one (event loop).</p><h4>Amp’s event loop</h4><p>To show you how the scheduler works — I’ll be using Amp. It is actually a whole ecosystem of libraries and tools for concurrent and async programming. Coroutines, promises, <em>await</em> (by using the <em>yield</em> keyword). Everything you need to start with asynchronous programming in PHP and much more than that.</p><h4>Willy Wonka &amp; the Time Factory</h4><p>Every time we wanted to use a particular scheduler in RxPHP we needed to provide a factory function that returned the desired instance. This is true for the event loop scheduler as well but this time we will also need to write a delay callback. I’m assuming you have already worked with RxPHP and asynchronous programming at least a little bit in the past so the following snippet should definitely ring a bell. But if your first reaction is along the lines of <em>Chronos almighty! </em>it’s probably a sign you should read up on what an event loop actually is and what it’s used for.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c1963dd07350ffb042bc173d4922ab2/href">https://medium.com/media/4c1963dd07350ffb042bc173d4922ab2/href</a></iframe><p>Here we create a new scheduler and pass it a callback that will be used every time a new action needs to be forwarded to the event loop. For this purpose we use the static <em>delay</em> function. It simply takes a callable (our future action) and throws it into the loop. It’s like moving everything one cog forward in our mechanical analogy and at the same time emitting a unit of made up energy that will be passed from the smaller gear to the bigger one. It’s just as easy.</p><h3>A scheduler’s post-mortem</h3><p>As you can see this time there was no need to manually start the scheduler. It’s all due to the fact that it has the ability to schedule its own start-up. The only thing left for us to do is to set the event loop in motion by calling <em>Loop::run(). </em>Now we will dissect the event loop scheduler and try to answer the question — how can it run all by itself?</p><h4>Tracing it all down</h4><p>Every time <em>subscribe</em> is called on an observable, eventually it’ll all boil down to calling <em>_subscribe</em> which uses the scheduler to enqueue an action using a variety of methods like <em>schedule, scheduleRecursive</em> or <em>schedulePeriodic</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed1f492279d99a68b3f4741450f451a7/href">https://medium.com/media/ed1f492279d99a68b3f4741450f451a7/href</a></iframe><p>Since <em>EventLoopScheduler</em> can’t respond to <em>schedule</em> by itself its parent’s implementation is used. It wraps our action in another callback that returns an <em>EmptyDisposable</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/728245967d335a90580f6c1be735525d/href">https://medium.com/media/728245967d335a90580f6c1be735525d/href</a></iframe><p>Then <em>EventLoopScheduler</em> builds a <em>CompositeDisposable</em> with <em>scheduleAbsoluteWithState</em> from both its own implementation and from its parent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05da7ad5b9b7e837816f1973315107ed/href">https://medium.com/media/05da7ad5b9b7e837816f1973315107ed/href</a></iframe><p>If the action is due it calls <em>EventLoopScheduler::scheduleStartup</em> which in turn calls <em>EventLoopScheduler::start</em>. It checks for new actions to dequeue and uses the provided delay callback to call its <em>start</em> method again. There is no way for the scheduler to start using too many resources as it only runs as long as its queue is not empty. When it’s done the cycle will be repeated only if another action is requested to be scheduled via an observable’s <em>_subscribe</em> method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbe1ac30ac34e356f62bc494de408714/href">https://medium.com/media/cbe1ac30ac34e356f62bc494de408714/href</a></iframe><h3>Summary</h3><p>This post should give you a thorough understanding of how RxPHP works with an event loop scheduler. We covered Amp but any event loop implementation should do as long as a proper factory method is provided. By now you should know how the event loop lets your RxPHP application be fully asynchronous without exposing the low-level internals (even though they’re worth learning).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c4d01d7e65e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-rxphp-schedulers-part-2-6c4d01d7e65e">Understanding RxPHP Schedulers (part 2)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding RxPHP Schedulers (part 1)]]></title>
            <link>https://medium.com/swlh/understanding-rxphp-schedulers-part-1-d3c0ab6eb881?source=rss-bcfcf82cb217------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c0ab6eb881</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[rxphp]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[reactivex]]></category>
            <dc:creator><![CDATA[Jakub Tapuć]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 21:19:14 GMT</pubDate>
            <atom:updated>2019-09-30T23:23:37.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*_BKV9uvKzQlXgad9JlSoXQ.png" /></figure><h3>Why you should care</h3><p>If you’ve ever found yourself wondering how RxPHP works under the hood then this is the right place for you to start learning about one of the most basic concepts used in this library — schedulers. Even if you think you’re satisfied with your current level of knowledge of RxPHP, grokking the concept of schedulers may prove beneficial to your overall understanding of how RxPHP is built and why it works the way it works.</p><p>Without further ado let us dig into the internals of schedulers!</p><h3>The big picture</h3><p>Similarly to other ReactiveX libraries every time you create and subscribe to an observable in RxPHP you are implicitly using schedulers. That’s right. Schedulers are the bread and butter of RxPHP.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1605024616f1f67a035fb103248e323b/href">https://medium.com/media/1605024616f1f67a035fb103248e323b/href</a></iframe><p>Even in the short snippet above there is a lot going on. First, we create an observable with <em>of</em> that emits one value and then we subscribe to it. In return, we get a <em>Disposable</em> as a handle than can be used to cancel the subscription. Internally, the <em>subscribe</em> method asks the scheduler to enqueue a piece of work (in this case our callback). As you can see there is no explicit call to the scheduler and still we’re using one because our callback needs to be scheduled somehow. It all happens through the scheduler even though we’re not dealing with a typical asynchronous use case with operators such as <em>delay</em>.</p><h3>What is a scheduler anyway?</h3><p>Scheduler is an object with an internal clock, used to enqueue a piece of work. Let that sink in. There are no constraints on this definition, no “sync”, “async” or “threading”. In its most general form the scheduler maintains a logical queue of actions (functions) to be executed. Every time you tell the scheduler to add an an action to the queue it gives you back a <em>Disposable</em> instance that you can use to cancel it and clean up the resources.</p><p>Schedulers are an intermediary between observables and the actual environment where the actions are executed. Since observables are decoupled from schedulers, the scheduler gives observables an execution context meaning that they govern the when (immediately, or in the future) and where (current thread, in the event loop, on another thread) of observables. To sum it up:</p><ul><li>Schedulers enqueue actions,</li><li>schedulers know when and where to execute actions,</li><li>schedulers maintain their own internal clock.</li></ul><h3>Types of schedulers in RxPHP</h3><h4><em>SchedulerInterface</em> is where it all begins</h4><p>Before we can discuss the individual schedulers used in RxPHP we need to talk a bit about the abstractions behind them. These abstractions could also be used to build <em>your own</em> schedulers (implementing a threading scheduler not present in the default distribution of RxPHP sounds like a pretty good idea! ⚡). Every scheduler in RxPHP must implement <em>SchedulerInterface</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47d516efeb0993b0ab309f65961422ea/href">https://medium.com/media/47d516efeb0993b0ab309f65961422ea/href</a></iframe><p>In this post we’re going to cover its first two methods. The <em>schedule</em> method takes a callable that will be executed with a delay (in milliseconds). <em>Now</em> returns the current value of the internal clock.</p><p>There is another, empty interface that simply extends <em>SchedulerInterface</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dc39876bcde868b83aff88d15887904/href">https://medium.com/media/7dc39876bcde868b83aff88d15887904/href</a></iframe><p>Its only purpose is to signal that its implementors are dealing with asynchronous scheduling of actions.</p><h4>ImmediateScheduler hates when things are delayed</h4><p>Probably (and hopefully) the easiest scheduler to master is the immediate scheduler. It directly implements <em>SchedulerInterface</em>. The cool thing about schedulers in general is that they can be used separately without the need to use observables at all; this will prove very useful later on when we acquaint ourselves with async schedulers. Let’s get our hands dirty and look at some actual code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21f7442390d601465bfa13372450aa4f/href">https://medium.com/media/21f7442390d601465bfa13372450aa4f/href</a></iframe><p>This was quite a lot to achieve something so simple so let’s get to it. First, we need to set a default (global, in fact) scheduler for our actions. We use <em>ImmediateScheduler</em> and pass it to the factory function. Then, upon subscribing to the observable its value is output to the console immediately.</p><p>If you’re still there you’re probably asking yourself now — <em>but what actually happened?</em> Let’s try to delve into the internals.</p><p>There are many static factory methods in the <em>Observable</em> class and <em>of</em> happens to be one of them. It returns an object of a funny class <em>ReturnObservable</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90e78877f594a8c55b39be815f36dec0/href">https://medium.com/media/90e78877f594a8c55b39be815f36dec0/href</a></iframe><p>When you call the <em>subscribe</em> method on an observable instance, the protected <em>_subscribe</em> method will eventually be called that asks the scheduler to enqueue some work associated with this particular kind of observable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/906c53911b045bee33105ab36de9f880/href">https://medium.com/media/906c53911b045bee33105ab36de9f880/href</a></iframe><p>So what the scheduler essentially does when <em>schedule</em> is invoked is just firing the callback and returning an empty <em>Disposable</em>. The method ensures that no delay has been set and throws an exception if one attempts to do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad7b656777afd0098910f7791cff4cde/href">https://medium.com/media/ad7b656777afd0098910f7791cff4cde/href</a></iframe><p>An astute reader might wonder — what about its clock? Well, the answer is pretty straightforward, <em>ImmediateScheduler</em> uses the system clock so nothing fancy happens underneath:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f0b70586bef2b977e29e91d32e01d9f/href">https://medium.com/media/4f0b70586bef2b977e29e91d32e01d9f/href</a></iframe><h4>Sorry, I lied to you</h4><p>Somewhere in the beginning of the article I listed three things that characterize a scheduler. One of them was:</p><blockquote>Schedulers enqueue actions.</blockquote><p>Normally this is a perfectly valid statement but for the immediate scheduler it’s a big fat lie. Why? <em>ImmediateScheduler</em> does not need a queue at all because all it does when it receives a piece of work is invoking it. Thus, every time an observable instructs the scheduler to enqueue something on its behalf it just runs whatever action it’s fed. When the work is done it returns an <em>EmptyDisposable</em> that acts as a kind of identity element since its <em>dispose</em> method does nothing it all.</p><h4>Other types of schedulers</h4><p>There are three other schedulers available for use in RxPHP. <em>VirtualTimeScheduler </em>and its two descendants: <em>EventLoopScheduler</em> and <em>TestScheduler</em>. I am going to present virtual time scheduler and event loop scheduler in the next part of this series.</p><h3>Summary</h3><p>By now you should have an idea of what schedulers are and what part they play in the RxPHP environment. You should be able to name different schedulers and know the inner workings of the immediate scheduler. You should be able to explain in detail how subscribing to an observable works and how actions in RxPHP are scheduled and then invoked.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c0ab6eb881" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-rxphp-schedulers-part-1-d3c0ab6eb881">Understanding RxPHP Schedulers (part 1)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>