<?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 Qing Zhong on Medium]]></title>
        <description><![CDATA[Stories by Qing Zhong on Medium]]></description>
        <link>https://medium.com/@qingzhong?source=rss-950f43c2aba2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rsalguQyWQcb24Pp.</url>
            <title>Stories by Qing Zhong on Medium</title>
            <link>https://medium.com/@qingzhong?source=rss-950f43c2aba2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 17:21:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@qingzhong/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Android Video Playback Tutorial (part2) — The structure of MP4 file]]></title>
            <link>https://medium.com/@qingzhong/android-video-playback-tutorial-part2-the-structure-of-mp4-file-cba021c6f67?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cba021c6f67</guid>
            <category><![CDATA[multimedia]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 13:06:35 GMT</pubDate>
            <atom:updated>2018-10-09T13:06:35.433Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Video Playback Tutorial (part2) — The structure of MP4 file</h3><p>In the last section, I went through some basic terms in video playback development.</p><p><a href="https://medium.com/@qingzhong/android-video-playback-part1-the-terms-you-need-to-know-8d581b13ae63">Android Video Playback(part1) The terms you need to know</a></p><p>In this section we will focus on container level, and use MP4 as an example to illustrate what does a container file looks like.</p><p>Here’s the checklist of today’s tutorial :</p><pre><strong>1. Structure of MP4 file<br>2. Metadata of MP4 file<br>3. Initialisation of a standard video player<br>4. Online video streaming</strong></pre><h3><strong>1.Structure of MP4 file</strong></h3><p>In the last section we go through the structure of the container file :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQgFFvvd3kjEoiaklZIUwQ.png" /></figure><p>But this may still looks a bit abstract to you, then lets go deeper.</p><h4><em>1.1 What is MP4 format</em></h4><p>Generally speaking, MP4 is actually just a standard which gets verified by ISO, which means that as long as you generates a MP4 file, it must follow the standard and definition from the ISO, just like a protocol that everyone follow.<br><br>Click this link-&gt;[<a href="http://xhelmboyx.tripod.com/formats/mp4-layout.txt">ISO standard for Mp4 file</a>]<br><br>As you can see in the definition, we define a lot of metadata&#39;s position, size. Lets take a look at the first few lines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iO7BUc-yswriv2YsjH1zcw.png" /></figure><p>With that being said, any container file includes MP4 are just structural files, the only differences are their data’s positions and headers and stuffs like that according to ISO standard. If you are interested you can check whats the definition and specification for other format like rmvb, mkv, AVI, or why some of them are suitable for online streaming while some don’t.</p><h3>2 .<em>The MetaData of a MP4 file</em></h3><p>About the metadata of a mp4 file, Apple has specified the details<br>(this is another version of mp4 which is aiming for QuickTime, but its almost the same so we can ignore the difference now)<br><br>Feel free to checkout the specification of the QuickTime MP4 [<a href="https://developer.apple.com/library/content/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-25706">Movie Atom</a>]</p><p>First of all, in the meta data, we called them Atom Header. Atom Header has two different types: 1. Leaf Atom 2. Container Atom. The former one contains a lot of information while the later one contains other Leaf or Container Atom. There&#39;s a hierarchy between container and leaf atom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*gEwHLZnKZCYmCizcdHQ53w.gif" /><figcaption>Movie Atoms for MP4 container file</figcaption></figure><p>It looks very complicated ，but for a player a lot of information are not really needed. The most important information is the <strong>Sample Table Atoms</strong>, which is the <strong>stbl </strong>atom header. It stores a table which maps the vide time and the sample’s position in the file(for example, which byte to which byte is the data for that), including the size of the sample as well.</p><h3>3 .How Player works</h3><pre>Usually a player consists of 4 parts<br><br><strong>1. Extractor<br>2. TrackRenderer<br>3. Load Controller<br>4. Source</strong></pre><p>Extractor will load the data from the source file(via HTTPS/HTTP), Load control module will control the strategy for buffering ,TrackRenderer will decode the data read from Source and then display them to the screen on your device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6u_03q4pptgSIHN--MOIpQ.png" /></figure><p>Well with Android APIs contexts, we can simplify the process as the below animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*moK56buYk0pauZleA3AxqQ.gif" /></figure><p>Before the player handles the data to renderer/decoder, extractor will need to read all the atom headers into the ram, for example the sample table we mentioned. Usually three tables will be initialised, one is for the time index, another one is the starting position of each sample, the last one is the size of each sample</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*dPWGg0ecK2_B75VQwmG7hQ.jpeg" /><figcaption>Table 1</figcaption></figure><p>If the player needs to start the playback from the 1 millesec.<br>from <strong>TABLE</strong> <strong>1</strong> we knew for the first milli sec, which sample do we need, from the second and third table we know whats the range of that sample inside the container (0–300th byte). Then our player will download the data and feed them to the renderer.</p><p>So when we <strong>seek </strong>to different position of the video, we knew exactly what parts of the data from the container we want to start downloading/buffering.</p><p>From everything above we know that before the video playback starts, we need to read and parse those atom headers(which is a time consuming work), which is also a bottleneck for online streaming’s waiting time. In the next section im gonna go through the <strong>Adaptive Streaming</strong>, which make use of the Fragmented MP4 technology to reduce the waiting time.</p><h3>4 .Online Video Streaming</h3><p>The only difference between online streaming and local video playback is the <strong><em>Source</em></strong>, one is local another one needs to be transferred via network. Obviously we don’t need to download the entire file into our ram, so we need to control the buffering and download strategy.</p><blockquote>For example, while user is watching the 10th second, we may just need to buffer all the way till 20th second.</blockquote><p>And the so called <strong>Progressive Downloading</strong> solves the problem.</p><p>It sounds like some very deep and complicated technology~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*UxFLJlvPddkg9GZBJii-sg.jpeg" /></figure><p>while its actually just HTTP. In Http 1.1 it defines something called <strong>Range</strong> in the headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WMm__rtCyTFvarU9PLeCQA.png" /></figure><p>With this tag you can specify the starting and the end byte you want to download from the source file. This is also the foundation of the break point downloading in a lot of browsers. Every time we disconnect and reconnect, we calculate the already downloaded file’s size and specify **Range** == current size+1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eaP0Q1Hz3YQNn8otmN7LBQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cba021c6f67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Video Playback(part1) The terms you need to know]]></title>
            <link>https://medium.com/@qingzhong/android-video-playback-part1-the-terms-you-need-to-know-8d581b13ae63?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d581b13ae63</guid>
            <category><![CDATA[multimedia]]></category>
            <category><![CDATA[video-player]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[exoplayer]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Mon, 08 Oct 2018 15:34:46 GMT</pubDate>
            <atom:updated>2018-10-09T13:07:15.364Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Video Playback Tutorial (part1) — The terms you need to know</h3><p>I’ve been thinking about publishing a series of video playback basics in Android for a long long time, and since I just got my visa done its time to get it done.</p><p>In this series Im gonna go through some basics in video playback development within or without Android contexts, then go deeper into the source code of a very famous open source video player library <a href="https://medium.com/google-exoplayer/exoplayer-2-1-whats-new-2832c09fedab">Exoplayer</a> . And explain certain components of it since they are quite hard to understand if don’t have any knowledge on video playback.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fsvdq1BWl4r8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dsvdq1BWl4r8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fsvdq1BWl4r8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8604e3a72794b39b17c11751cf77a1d2/href">https://medium.com/media/8604e3a72794b39b17c11751cf77a1d2/href</a></iframe><p>So , in this section, Im gonna cover the below topics:</p><p><strong>1. What is Codec<br>2. What is Container format file<br>3. Video/Audio files processing</strong></p><h3><strong><em>1.What is Codec</em></strong></h3><p>When speaks of video or audio , I guess most of us have heard of these two terms <strong>Encode</strong> and <strong>Decode</strong>. The codec we mentioned is actually a programme(or API), this programme can help us to decode and encode raw Video/Audio files. In Wikipedia, they define codec as follow:</p><blockquote>A video codec is an electronic circuit or software that compresses or decompresses digital video. It converts raw (uncompressed) digital video to a compressed format or vice versa. In the context of video compression, “codec” is a concatenation of “encoder” and “decoder” — a device that only compresses is typically called an encoder, and one that only decompresses is a decoder.</blockquote><p>But problem comes , we all knew MP4 , AVI or RMVB format , but whats the relationship between them?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fTrDA82I94nrrN_kToakg.png" /><figcaption>what are they</figcaption></figure><p>First of all, <strong>Encode</strong> is compression, <strong>Decode</strong> is decompression. The foundation of video is actually collections of images, or frames. When a collection of images keep being displayed in front of human eyes(a smooth animation or movie requires 24 frames in a second), then human eye will deceive our brain telling us its moving while they are just collections of images(or you can say a very fast PPT).</p><p>We can start doing some Math, assume that 1280X720 p image( high resolution, width 1280 pixels and height 720 pixels), so it’s size is 1280X720X3 bytes, which is 2.7MB. For a 60s short movie we need at least 60(seconds)*24(frames)*2.7MB = 3.9GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSSBVi9AdALlXwn5biRvcw.png" /></figure><blockquote>The reason why we need to multiply by 3 is that one pixel need at least 3 colors ( <strong><em>RGB</em></strong> ), one color needs one byte (remember in color.xml color format is #ffffff right? ).</blockquote><p><strong>This is definitely not acceptable!</strong></p><p>That’s why we need codec, they compress large files to smaller files by using certain algorithm, this is so called <strong>Encode</strong>. But in the client side, we need real images to be displayed, so when it comes to display part, we need to decompress them which is <strong>Decode</strong>.</p><p>Anyway, video decoding/encoding is a very complicated process, but luckily we have a lot of available tools and APIs for encoding or decoding the video/audio files. Some of the popular video encoding/decoding standards are :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AaQTXLmhEMe74w1GmWgGA.png" /></figure><p>Let’s use an example to illustrate one of the technology that helps us to compress images/videos.</p><p>Let’s imagine a scenario. In one scene of a movie, the actor was crying into tears and standing still in a silent and empty central park, time seems to be stopped for a whole 10 seconds. For this kind of “static” scenes, the compression algorithm will only take the first frame make it as a base. Then for the rest of the frames we only store the difference between frames instead of the complete image. This will compress the original raw file a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPisKCcdF2Uhx8nAwvGfzA.png" /></figure><p>Of course this is just tip of the iceberg for encoding/decoding technology, we dont want to explore too deep now.</p><p>In addition, Codec technology includes <strong>Video</strong> and <strong>Audio</strong>. Because Audio is sound wave but Video is images, they are different in their nature. In this series we are gonna mainly focusing on the Video part.</p><p>Back to the Codec, since Codec is a programme under certain standards, we will have different implementations under different standard. For example, in Android, google provides Codec API , it wraps things up and encapsulate some native apis under certain standard.</p><h3>2. What is Container format file</h3><p>When we download movie from pirate site, we usually see formats like mp4, avi,rmvb, or mkv. We used to call them video files, but thats not very professional.</p><p>Technically we call them <strong>Container</strong> File, because this file contains a lot of data includes not only video but also audio, some container even has subtitle data inside. It may sounds scary to you at the first glance but its actually just a structural file. We refer it as “structural” because all the video/audio/text data are putting under certain position of the file under certain standards(which makes player easy to parse them).</p><p>Container file is a product from raw files getting compressed, also besides audio/video data, it also contains other metadata like duration, movie title… etc.</p><p>Here’s a graph showing how a container looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQgFFvvd3kjEoiaklZIUwQ.png" /></figure><p>It mentions about Track, its a term in video playback, which identifies different data like audio or video.</p><p>But in mp4 container the most significant data is the <strong>MetaData</strong>, it contains a lot of raw data for the movie, like duration, file size, also a <strong>Index Table</strong>, this table contains starting position in the file for different track data, because each track will be segmented into samples(one sample is a independent playable video or audio , base in millesec), the MetaData will hold a sample table/ index table, it records each sample’s starting position and size, also its mapping time for the movie.</p><h3>3.Video processing- from backend to frontend</h3><p>Lets begin with a real world scenario</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z1Ej28ZVldcU1cUYWk98Q.png" /><figcaption>whole process of digitalising a film to video</figcaption></figure><p>The director file the movie which is <strong>Raw File</strong>, the film is the original data which is collections of images/frames. We use software to digitalise them and compress it and put them into a <strong>Container</strong>. For online streaming purpose we process them into different resolutions and store them into server or local CDN. Then you device will starting requesting the file and the playback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZsFNROS5yos1LOCztHOK_Q.png" /></figure><p>Next Section :</p><p><a href="https://medium.com/@qingzhong/android-video-playback-tutorial-part2-the-structure-of-mp4-file-cba021c6f67">https://medium.com/@qingzhong/android-video-playback-tutorial-part2-the-structure-of-mp4-file-cba021c6f67</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d581b13ae63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Message Queue — What every Android Developer Needs to Know]]></title>
            <link>https://medium.com/@qingzhong/understanding-message-queue-what-every-android-developer-needs-to-know-3490f4f48591?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3490f4f48591</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Fri, 18 May 2018 10:14:03 GMT</pubDate>
            <atom:updated>2018-05-18T10:14:03.431Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post Im gonna share a nice design which is used in lots of android applications or libraries, the <strong>Message Queue</strong> !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*lsp9Q_oX5Tispf_y." /></figure><p>Im gonna start with an simple example , then finally borrow ideas from Java and Android system source code to further demonstrate how we can fully make use of the <strong>Message Queue</strong> design to optimize our code and make them more readable !</p><h3>1.Network Request like Volley</h3><p>I believe most of us have used a Http Network library called <a href="https://github.com/google/volley"><strong>Volley</strong></a> . The underline implementation for Volley to do http call is actually from HttpUrlConnection or HttpClient(based on the device’s system version), and other extra features like thread controls, cache and callback are actually implemented on top of them. <strong>And the key for the library is to submit and process http requests.</strong></p><p>The most naive design is to use a single thread(not UI main thread in android) to keep polling the first request from the queue, process it and then pop it out from the queue. Also remember to fire the according callback after the process of the request is done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b032a3dbf7e6dcb8fc7a2026dcffdfc7/href">https://medium.com/media/b032a3dbf7e6dcb8fc7a2026dcffdfc7/href</a></iframe><blockquote><em>The above code is all we need for super simplified http network library like </em><strong><em>Volley</em></strong><em> ! Even though we didnt implement cache, or probably synchronization, but the core of Volley is similar like it, using queue to handle the reuqest. Thats it! wooow</em></blockquote><h3>2.Send Delayed Message</h3><p>Another interesting stuff in android app is to send <strong>deplayed</strong> Messages. Its a bit different from the network use case since the later one doesn’t care about the executions sequence of the request, but the delayed message system needs it.</p><p>For example if we submit an message <strong>A</strong> for being executed <strong>3</strong> sec later and another message <strong>B</strong> for being executed <strong>1</strong> sec later, the expected result is <strong>A</strong> should be executed after the execution of <strong>B</strong>.</p><p>While in this case we can use an LinkedList to replace the Queue(while in Java a LinkedList can be a Queue instance), then insert messages based on their execution time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ed5ab859f5b169ae3f3482840bb5fe2/href">https://medium.com/media/3ed5ab859f5b169ae3f3482840bb5fe2/href</a></iframe><ol><li>we use an linkedlist to store the messages because linkedlist has a smaller time complexity for inserting.</li></ol><blockquote><em>2.we used two dummy head and tail in case of potential null check, if we are having null for head or tail we need to do extra work like this: </em><em>if(head == null){ head = message } else if( tail == null ){head.next = message; tail = message}</em></blockquote><p>3.when inserting delayed message, we need to find the first earlier message than it.</p><p>when the message we wanted to insert execTime is 3, we need to put it between message 1 and message 5.</p><p>the api can be very simple then:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb81914ecdd76c85f00f3147e969b68c/href">https://medium.com/media/bb81914ecdd76c85f00f3147e969b68c/href</a></iframe><p>Don’t you feel the code above look very familiar for you? Yes , this is exactly how Android’s <a href="https://developer.android.com/reference/android/os/Handler">Handler</a> do for posting delay message. Only that android system has extra code for recycling the Message object. But the core is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dZIirK-edmizkUZ8." /></figure><p><strong>Lastly , we can think a little bit more, Is the above code really making a exact 3 seconds delay?</strong></p><p>The answer is no….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*zmO9ZPdjIWDlB2Ry.jpg" /></figure><p><strong>if Message A needs to delay for X sec, while current time is Y, our system can ensure the A wont be executed early than X+Y</strong></p><p>This is pretty easy to understand, as you will never know how long does it take for executing all the preceding messages. If we want a strict time based system, we may need an Alarm.</p><h3>3.Simple ThreadPool</h3><p>Speaking of thread pool, most of the articles online are trying to teach us how to use their API.</p><p>But come on … we dont need an API doc, we need to understand how it works right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*MbG-bPFcLJuXkRbm." /></figure><p>In this section, im gonna use Queue and Thread class to implement the simple threadpool</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc751a67055818e1ef391a14ba418403/href">https://medium.com/media/dc751a67055818e1ef391a14ba418403/href</a></iframe><p>Thats it, we just finished an simple Thread Pool, and again, this is also how Java’s ThreadPool works. Of course it should have other features like shutdown threads , exception handling etc which we dont have right now in this simple thread pool implementation.</p><p>the api for our implementation is also very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdbe588bbb262782767e8f025314b8fc/href">https://medium.com/media/bdbe588bbb262782767e8f025314b8fc/href</a></iframe><p><em>Originally published at </em><a href="https://gist.github.com/richardissuperman/8dc856dcf9f40b35f50aec4fa63db10f"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3490f4f48591" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Message Queue — What every Android Developer Needs to Know]]></title>
            <link>https://medium.com/@qingzhong/the-message-queue-design-weve-been-missing-in-android-development-b9dc10ea45c7?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9dc10ea45c7</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Wed, 02 May 2018 10:55:37 GMT</pubDate>
            <atom:updated>2018-05-18T10:10:04.219Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post Im gonna share a nice design which is used in lots of android applications or libraries, the <strong>Message Queue</strong> !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*lsp9Q_oX5Tispf_y." /></figure><p>Im gonna start with an simple example , then finally borrow ideas from Java and Android system source code to further demonstrate how we can fully make use of the <strong>Message Queue</strong> design to optimize our code and make them more readable !</p><h3>1.Network Request like Volley</h3><p>I believe most of us have used a Http Network library called <a href="https://github.com/google/volley"><strong>Volley</strong></a> . The underline implementation for Volley to do http call is actually from HttpUrlConnection or HttpClient(based on the device’s system version), and other extra features like thread controls, cache and callback are actually implemented on top of them. <strong>And the key for the library is to submit and process http requests.</strong></p><p>The most naive design is to use a single thread(not UI main thread in android) to keep polling the first request from the queue, process it and then pop it out from the queue. Also remember to fire the according callback after the process of the request is done.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b032a3dbf7e6dcb8fc7a2026dcffdfc7/href">https://medium.com/media/b032a3dbf7e6dcb8fc7a2026dcffdfc7/href</a></iframe><blockquote><em>The above code is all we need for super simplified http network library like </em><strong><em>Volley</em></strong><em> ! Even though we didnt implement cache, or probably synchronization, but the core of Volley is similar like it, using queue to handle the reuqest. Thats it! wooow</em></blockquote><h3>2.Send Delayed Message</h3><p>Another interesting stuff in android app is to send <strong>deplayed</strong> Messages. Its a bit different from the network use case since the later one doesn’t care about the executions sequence of the request, but the delayed message system needs it.</p><p>For example if we submit an message <strong>A</strong> for being executed <strong>3</strong> sec later and another message <strong>B</strong> for being executed <strong>1</strong> sec later, the expected result is <strong>A</strong> should be executed after the execution of <strong>B</strong>.</p><p>While in this case we can use an LinkedList to replace the Queue(while in Java a LinkedList can be a Queue instance), then insert messages based on their execution time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ed5ab859f5b169ae3f3482840bb5fe2/href">https://medium.com/media/3ed5ab859f5b169ae3f3482840bb5fe2/href</a></iframe><ol><li>we use an linkedlist to store the messages because linkedlist has a smaller time complexity for inserting.</li></ol><blockquote><em>2.we used two dummy head and tail in case of potential null check, if we are having null for head or tail we need to do extra work like this: </em><em>if(head == null){ head = message } else if( tail == null ){head.next = message; tail = message}</em></blockquote><ul><li>when inserting delayed message, we need to find the first earlier message than it.</li></ul><p>when the message we wanted to insert execTime is 3, we need to put it between message 1 and message 5.</p><p>the api can be very simple then:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb81914ecdd76c85f00f3147e969b68c/href">https://medium.com/media/bb81914ecdd76c85f00f3147e969b68c/href</a></iframe><p>Don’t you feel the code above look very familiar for you? Yes , this is exactly how Android’s <a href="https://developer.android.com/reference/android/os/Handler">Handler</a> do for posting delay message. Only that android system has extra code for recycling the Message object. But the core is the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dZIirK-edmizkUZ8." /></figure><p><strong>Lastly , we can think a little bit more, Is the above code really making a exact 3 seconds delay?</strong></p><p>The answer is no….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*zmO9ZPdjIWDlB2Ry.jpg" /></figure><p><strong>if Message A needs to delay for X sec, while current time is Y, our system can ensure the A wont be executed early than X+Y</strong></p><p>This is pretty easy to understand, as you will never know how long does it take for executing all the preceding messages. If we want a strict time based system, we may need an Alarm.</p><h3>3.Simple ThreadPool</h3><p>Speaking of thread pool, most of the articles online are trying to teach us how to use their API.</p><p>But come on … we dont need an API doc, we need to understand how it works right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/0*MbG-bPFcLJuXkRbm." /></figure><p>In this section, im gonna use Queue and Thread class to implement the simple threadpool</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc751a67055818e1ef391a14ba418403/href">https://medium.com/media/dc751a67055818e1ef391a14ba418403/href</a></iframe><p>Thats it, we just finished an simple Thread Pool, and again, this is also how Java’s ThreadPool works. Of course it should have other features like shutdown threads , exception handling etc which we dont have right now in this simple thread pool implementation.</p><p>the api for our implementation is also very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdbe588bbb262782767e8f025314b8fc/href">https://medium.com/media/bdbe588bbb262782767e8f025314b8fc/href</a></iframe><p><em>Originally published at </em><a href="https://gist.github.com/richardissuperman/8dc856dcf9f40b35f50aec4fa63db10f"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9dc10ea45c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava for 100% beginners (part5-use case from Netflix)]]></title>
            <link>https://medium.com/@qingzhong/rxjava-for-100-beginners-part5-use-case-from-netflix-2df6afa6dcc9?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df6afa6dcc9</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Sun, 01 Jan 2017 10:43:09 GMT</pubDate>
            <atom:updated>2018-10-08T09:12:37.912Z</atom:updated>
            <content:encoded><![CDATA[<p>In case you need to review the last post::</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part4-some-magics-from-flatmap-family-2ddb2719bab8">https://medium.com/@qingzhong/rxjava-for-100-beginners-part4-some-magics-from-flatmap-family-2ddb2719bab8</a></p><p>I know most of you are probably tired of learning some “basic” operators like I first got in touch of RxJava. I was always wondering, if anyone from a big company , big team, has some proofs of technology to show us how they utilise RxJava since most of the blogs and articles online were pretty much the same as my previous 4 ones-&gt;basic operators…..</p><p>I didnt get lucky until i found this amazing youtube video..</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_t06LRX0DV0%3Fstart%3D2115%26feature%3Doembed%26start%3D2115&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_t06LRX0DV0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_t06LRX0DV0%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/69faae4ae6c1959728ee73171ccbfa6a/href">https://medium.com/media/69faae4ae6c1959728ee73171ccbfa6a/href</a></iframe><p>This video illustrates one real use case from Netflix, and you know what, better yet,the guy speaking in this video is <strong>Ben Christensen</strong>, the father of RxJava who worked for Netflix at that time(now go Facebook…). I cant name a better example for beginner than this one.</p><p>So i made an sample project to illustrate what Ben describes in this video, noted that this use case is happening in the backend, but since im an Android developer… i made the sample project an Android Studio project :(</p><p><a href="https://github.com/richardissuperman/netflixrxexample">richardissuperman/netflixrxexample</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOTA_9MzWLUNlXu98-d9Yg.png" /><figcaption>this is the overall structure of this sample</figcaption></figure><p>So, back to the example. Netflix has this service called, VideoService, which you can get a list of the user’s favourite videos. But the video objects are not completed ones, if you want to get each video’s bookmark, rating or metadata, you have to make separate api calls and combine them as one.</p><p>So here’s the bean object for <strong>Video</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*jO33wBsfn0FQhzIn7PuIlA.png" /></figure><p>and we also have an VideoService class for retrieving data from API call</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*fPiPSjsEye5244XII7BWmA.png" /></figure><p>Lets say, we wanna retrieve the first 10 video objects and get their bookmarks, ratings and metadata.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*rgD0qz63uT4DO1RkApQIUQ.png" /></figure><p>Beyond this point, we get 10 video objects!</p><p>Whats next ? its time to handle each video objects, get the video objects’ bookmark, ratings and metadata. Our goal is to run this 3 task in parallel, combine them eventually.</p><p>So first of all, we need to use flatmap to handle each video object, cause we need to make nested api call. Other than that, we have to combine the 3 api calls, which im gonna introduce one new operator-&gt;<strong>zipWith()</strong></p><p><a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX - Zip operator</a></p><p>I assume that you read the doc above and understand what it does. If we have one observable which emit one bookmark object by using a video’s videoID, one observable which emit one metadata object and the last observable emit rating object. All we have to do is <strong>zipWith() </strong>these 3 observable, tell RxJava how we wanna combine them, then you get a new observable which combine all 3 fields of data into one <strong>Video</strong> object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*N87JhcspYM9r9KdYDyuXwQ.png" /></figure><p>I think most of you guys may probably got stuck on the usage of flatMap(), if thats the case, please go back to previous sessions for the detail of flatMap() ….</p><p>Happy new year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df6afa6dcc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava for 100% beginners (part4-some magics from flatMap family)]]></title>
            <link>https://medium.com/@qingzhong/rxjava-for-100-beginners-part4-some-magics-from-flatmap-family-2ddb2719bab8?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ddb2719bab8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Wed, 28 Dec 2016 10:50:46 GMT</pubDate>
            <atom:updated>2018-10-08T09:09:01.527Z</atom:updated>
            <content:encoded><![CDATA[<p>In case you need to review the last post:</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part3-switching-threads-3ff305619f56">RxJava for 100% beginners (part3-switching threads)</a></p><p>When talking about RxJava’s operators, the most difficult ones belong to the <a href="http://reactivex.io/documentation/operators/flatmap.html">flatMap</a> family. In this session we are gonna review the basics of flatMap() operator, once you master the flatMap(), its always easier to understand other operators like concatMap().</p><p><a href="http://reactivex.io/documentation/operators/flatmap.html">ReactiveX - FlatMap operator</a></p><p>in the reactive world, sometimes we need to extend our element from the stream. Lets review our previous example, the very first one of loading bitmap from files in different folders.</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part-2-write-your-code-in-a-more-elegant-way-ccadfe61bb81">RxJava for 100% beginners(part 2-write your code in a more elegant way)</a></p><p>in the naive approach , we need to have two layer of for loops, to traverse all the files and transform those “png” format ones into bitmaps. In this case , the the first step is we list all folders, second step we list all the files from them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrhTWzyy2FT6MVL7VL2twA.png" /></figure><p>but think about this, the files in the second for loop, where do they come from? They come from the first loop’s folder element. Which means the folder element generates more “files element”, and eventually , we just care about the the file element, which is gonna be used to be transformed into bitmap.</p><p>Lets assume that we have a list of files, and we wanna transform them into bitmaps, which operator can we use? map() of course!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b81ce1c0b222a07b6d2004b0a9aca70/href">https://medium.com/media/4b81ce1c0b222a07b6d2004b0a9aca70/href</a></iframe><p>This is a very simple File →Bitmap transformation.</p><p>But in the very first example, we need to transform Folders →Bitmap. There’s a middle layer we have to handle, which is transforming a list of folders to a list of bitmaps.</p><p>Luckily, we have flatMap() here, which is the one can help us out for this kind of “nested extension of lists”. flatmap() is an operator which source a <strong>stream of elements A</strong>, generate <strong>new streams of elements B</strong> base on each element A from the source, and eventually <strong>merge</strong> the newly created <strong>streams</strong> of element B into <strong>one stream of element B</strong>.</p><p>In our case, the stream of element A is the Folders, the stream of element B is the list of Bitmap we handle in the final subscriber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Hs2idFhTkajya9gXwo27A.png" /></figure><p>lets check out the codes to demonstrate the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d803ae0af92046c9e188fdc65aa27a/href">https://medium.com/media/b0d803ae0af92046c9e188fdc65aa27a/href</a></iframe><p>So, flatMap() can be very helpful when handling nested callbacks/multiple for loops/ <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)">Pyramid of doom</a>/ callback hell. in the later sessions we are gonna go through some use cases of combinations of multiple operators.</p><p>Another important operator in the flatmap family is concatMap().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mnw0Sh3mNQ9Cm6VotGZv2Q.png" /></figure><p>The only difference is that concatMap() will preserve the sequence of the final elements based on the sequence of the first stream while flatMap() doesn’t.</p><p>Next Section:</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part5-use-case-from-netflix-2df6afa6dcc9">RxJava for 100% beginners (part5-use case from Netflix)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ddb2719bab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava for 100% beginners (part3-switching threads)]]></title>
            <link>https://medium.com/@qingzhong/rxjava-for-100-beginners-part3-switching-threads-3ff305619f56?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff305619f56</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Thu, 08 Dec 2016 09:55:21 GMT</pubDate>
            <atom:updated>2018-10-08T09:07:46.038Z</atom:updated>
            <content:encoded><![CDATA[<p>In last section, we went through a pretty solid use case for RxJava. In this section lets start with some popular operators and some nice use cases for them.</p><p>In case you need to review the last post:</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part-2-write-your-code-in-a-more-elegant-way-ccadfe61bb81">RxJava for 100% beginners(part 2-write your code in a more elegant way)</a></p><ol><li><strong>Map</strong></li></ol><p><a href="http://reactivex.io/documentation/operators/map.html">ReactiveX - Map operator</a></p><p><strong>map</strong> is the most frequent use operator in RxJava, it will modify every element from the upper stream to another and return a new stream of the modified elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zoL_cWqivcmlzD9T5g1wg.png" /></figure><p>the below example will obtain source from an ArrayList, form a source Observable. Then we apply a change to the source by adding 1 to each Integer, and change it to an String by attaching some text to the Integer.</p><p>Eventually we start calling the subscribe() method and let the final Observable start emitting elements, which are all String.(note, <strong><em>Observable will not start emitting elements unless you call subscribe()</em></strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNQULS1ac3a99JiU7qo9LQ.png" /></figure><p>please also take a look at the object type of each call() method’s parameter and return value from Func1 interface we created for map(). They will change based on the operations we perform over those elements.</p><p><strong><em>1:The current call() method’s parameter type is always the same as the upper Observable’s generic type(it emits , you handle XD).</em></strong></p><p><strong><em>2:The final Subscriber’s generic type will always be the same as the final Observable’s generic type.</em></strong></p><p><strong>2.subscribeOn() &amp;&amp; observeOn()</strong></p><ul><li><a href="http://reactivex.io/documentation/operators/subscribeon.html">ReactiveX - SubscribeOn operator</a></li><li><a href="http://reactivex.io/documentation/operators/observeon.html">ReactiveX - ObserveOn operator</a></li></ul><p>RxJava can help developers to switching threads very easily, with subscribeOn() and observeOn() operators, we can change thread execution by just define the thread pool you wanna choose from .</p><p>Lets try the subscribeOn() first. The definition of subscribeOn() from RxJava’s wiki is:</p><blockquote>Many implementations of ReactiveX use <a href="http://reactivex.io/documentation/scheduler.html">“</a><a href="http://reactivex.io/documentation/scheduler.html">Schedulers”</a> to govern an Observable’s transitions between threads in a multi-threaded environment. You can instruct an Observable to do its work on a particular Scheduler by calling the Observable’s SubscribeOn operator.</blockquote><blockquote>The <a href="http://reactivex.io/documentation/operators/observeon.html">ObserveOn</a> operator is similar, but more limited. It instructs the Observable to send notifications to observers on a specified Scheduler.subscribeOn()</blockquote><p>hmm, but this doesnt look helpful at all….. So Im gonna summarise it in one sentence:</p><p><strong>subscribeOn() change the thread for emitting the source Observable’s elements, no matter where you put it in your “chain”.</strong></p><p>Lets take a look at an example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/414240bd36b95af459a672740603b236/href">https://medium.com/media/414240bd36b95af459a672740603b236/href</a></iframe><p>this time instead of obtain a source from an arraylist, i create my own logic, it almost does the same thing.form line 4- line 9, i emit Integers 1–3 and then completes emitting elements. Every time I emit an Integer , I will Log the current thread’s name. And since I apply the subscribeOn() operator on the source Observable, we can expect that the the emitting source process will be run in an thread from the IO thread pool maintained by RxJava(the scheduler parameter we pass into the subscribeOn() is the thread pool we assign to run in).</p><p>So lets run the code and see hows the log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iC2q6R5EQ8sgR06K_2tKg.png" /><figcaption>nice!</figcaption></figure><p>ok, thats pretty nice! we manage to change the thread for emitting the element from the source Observable.</p><p>what if we change the position where we apply this operator?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46e8e3c417622241c211f8478497ff78/href">https://medium.com/media/46e8e3c417622241c211f8478497ff78/href</a></iframe><p>now we change the subscribeOn() to be called after the first map(). Before we run the code, lets think about it first. Since subscribeOn() is for changing the source emission, will it has any difference if we put subscribeOn() in different place of the code?</p><p>NO! It wont! right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*9E9qKOCe9IGIsysMg5JDPQ.jpeg" /></figure><p>if dont believe it, we can try it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WFRlI5ZnfGtcUUUFKhYIUg.png" /></figure><p>haha, its still the same, which proves what i just said, it doesnt matter where you calls it, it will always work for the emitting the source Observable’s element. You can even try calling it multiple times, the result will be the same.(if you call subscribeOn() multiple times, only the first one will work, you can take some time and think about it.) Try the below example!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8e4e07728095520dc54fc7eea21118d/href">https://medium.com/media/d8e4e07728095520dc54fc7eea21118d/href</a></iframe><p>Ok，lets talk about observeOn() since we finished studying subscribeOn()!</p><p><strong>observeOn() change the thread for codes which are below observeOn() on.</strong></p><p>Talk is cheap show me the code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZQ_lTW5mzXU-lKKWPni7A.png" /></figure><p>and lets check out the logs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abtjpt1bPyvUHInn9szJ7Q.png" /></figure><p>exactly what we expected!</p><p>So by using subscribeOn() and observeOn(), we can easily achieve Android’s “process in the background thread, display in the main thread” pattern, now I think you can have a better understanding on the example from the previous section right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhhCqAlZ-wvSFQlZPyhuAQ.png" /><figcaption>process the bitmap in a new thread, and display them in Android’s main thread</figcaption></figure><p>in the next section, im gonna talk about some other useful operators then we will start diving into some “real world” use cases from Ben Christensen, the father of RxJava.</p><p>Next Section:</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part4-some-magics-from-flatmap-family-2ddb2719bab8">RxJava for 100% beginners (part4-some magics from flatMap family)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff305619f56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava for 100% beginners(part 2-write your code in a more elegant way)]]></title>
            <link>https://medium.com/@qingzhong/rxjava-for-100-beginners-part-2-write-your-code-in-a-more-elegant-way-ccadfe61bb81?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccadfe61bb81</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[rxjava]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Tue, 06 Dec 2016 10:22:04 GMT</pubDate>
            <atom:updated>2018-10-08T09:06:11.362Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last section I introduced some basics from functional programming, in this section we are gonna go through the real deals! RxJava!</p><p>In case you need to review the last post:</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part-1-1ab9081f2a34">RxJava for 100% beginners(part 1)</a></p><p>There is a very nice example which I wanna borrow from, if anyone of you can read chinese, you are encouraged to read the original here:</p><p><a href="http://gank.io/post/560e15be2dca930e00da1083">给 Android 开发者的 RxJava 详解</a></p><p>if not, i think i can just copy paste the example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsjg87HqAw4vrjyajRdRMQ.png" /></figure><p>in the above example, we are trying to :</p><ol><li>traverse a list of folder</li><li>traverse every file from the folder list</li><li>load the files which are “png” format and construct them as Bitmap</li><li>load the bimap to a “View”(do it in the UI thread to avoid exception)</li></ol><p>noted that except for step 3, every step else will be executed in a new Thread other than UI thread.</p><p>Is this example complicated? Well that depends, but one thing Im almost sure is that : These few lines of code is hard for expanding its functionalities. Lets say if we want to just <strong>take the first 10 “png” file(I guess we have to use a global variable as a counter right, which breaks the rule of functional programming XD) </strong>? or if we want to traverse the files in <strong>Thread A</strong>, and then process the files to images in <strong>Thread B(most naive way will be using a new Thread().start(), but the code will be nasty)</strong>?</p><p>Just Imagine how complicated your code will be after the expansion in a normal way. And even if I believe you are a great software engineer, you manage to solve it, you teammates who are working on the same project will be like:”What the hell is these” when they pull your code change…..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59_x_00U4BMxFyHdiMitPA.jpeg" /><figcaption>what have done to the code?</figcaption></figure><p>so lets check out how RxJava can handle it better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwmOEJrIvOTbXczT22ZFuw.png" /></figure><p>if we want to achieve the those extra functionalities above -&gt;</p><p>1.take only the first 10 element. 2.switch threads between traversing files and loading bitmap</p><p>we just have to add few more “operators” (which is a term from RxJava, it refers to the way we wanna change the current stream).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CNg_7P0fiBB1me510S-fA.png" /></figure><p>I believe that there are a tons of “operators” which you are not familiar with . But thats totally fine, I will go through them one by one in the following sections, right now all you need to do is to admit that the code is much much cleaner and more readable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*mj8umH3csWa3CDSFj9orgQ.gif" /><figcaption>oh yeah!</figcaption></figure><p>So By using RxJava,</p><ol><li>we flatten our code in a very elegant way, <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)">code pyramid of doom</a> is no longer there!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Bpd-185aUudUUQLxl6tebQ.jpeg" /><figcaption>code pyramid of doom</figcaption></figure><p>2. switching threads for different operations are easier than before!</p><p>So before we start to dive into those “operators”, there’s some conceptsI want you to keep in mind.</p><ol><li>RxJava, or general functional programming may not be a ideal tool to boost up your performance(if you have any performance issue in your app).Its just a new programming paradigm which helps you to have a cleaner and more readable code, as well as facilitates your abstract thinking and bring them to code without caring too much on the implementation details(like how to traverse a collection, how to change thread).</li><li>In RxJava, every time we use a “Operator” to operate on an “Observable” (which is the “event stream” we keep talking about), we manage to get a new “Observable”. For beginners , I don’t encourage you to go too deep into how RxJava implement this “feature”, you just have to know that the “event stream” will be changed to a new one, everything else is built on top of this, thats all you have to care about.</li></ol><p>So thats it for section2, lets cover some most popular operators from RxJava in the next section!</p><p>Next Section:</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part3-switching-threads-3ff305619f56">RxJava for 100% beginners (part3-switching threads)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccadfe61bb81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJava for 100% beginners(part 1)]]></title>
            <link>https://medium.com/@qingzhong/rxjava-for-100-beginners-part-1-1ab9081f2a34?source=rss-950f43c2aba2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ab9081f2a34</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Qing Zhong]]></dc:creator>
            <pubDate>Fri, 02 Dec 2016 09:07:44 GMT</pubDate>
            <atom:updated>2018-10-08T09:04:01.715Z</atom:updated>
            <content:encoded><![CDATA[<p>I believe that most of the Android developers are well aware of the existence of “Reactive Programming/RxJava” nowadays. You can always see blog posts related to RxJava in every single Android Weekly email in the past few months(Im not kidding…).</p><p>However, its a bit hard for beginner who doesn’t have knowledge about functional programming to adopt the syntax from RxJava. In Scala, you can find a lot of operators similar to RxJava’s, like map(), flatmap(),filter()…. If you tried Scala or any other functional programming language (Which RxJava borrow ideas and syntaxs from)before, you may have some advantages over those who doesn’t. But in this series, Im gonna go through some basics of functional programming first in case you don’t have any idea what it is. Luckily in Java8, we have <a href="http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html">Stream API </a>, the “Stream” class is very similar to “<a href="https://github.com/ReactiveX/RxJava/wiki/Observable">Observable</a>” from RxJava, so we are gonna pick up some stuffs from Java8 Stream API in order to understand RxJava’s Observable.</p><p>So here we are, lets get started!</p><p><a href="http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html">Processing Data with Java SE 8 Streams, Part 1</a></p><p>So for beginners, the advantages for Functional Programming can be 2 major one:</p><ol><li>Function can be used as a parameter to other functions, thats the so called “first-class object”.</li><li>It treats operations like “functions” in the math, we only care about results, or output from the last function to avoid caring about state changing , mutable object ..</li></ol><blockquote>It treats <a href="https://en.wikipedia.org/wiki/Computation">computation</a> as the evaluation of <a href="https://en.wikipedia.org/wiki/Function_(mathematics)">mathematical functions</a> and avoids changing-<a href="https://en.wikipedia.org/wiki/Program_state">state</a> and <a href="https://en.wikipedia.org/wiki/Immutable_object">mutable</a> data- Wikipedia</blockquote><p>In RxJava/Java8 Stream API, they support lambda expressions, which reflect the first advantage above. Lets take an example of this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71f11a8244401150b582d1e996ac91a5/href">https://medium.com/media/71f11a8244401150b582d1e996ac91a5/href</a></iframe><p>lets take a look at the difference between line 11 and line 21, they both print String “action start”, but the second one is much shorted, no need to create the instance of the interface “NewAction” and override its “call” method anymore, we simply just code the method’s body and pass it to execute(). That’s not magic !</p><p>In Java 8, you can enjoy this lambda expression if the <strong>interface </strong>you wanna create instance from just contains <strong>one method</strong>, then you can just put the method body to where you wanna it to be without creating the instance of the interface in your code.</p><p>However, we are not really using function as parameter here, its just the help from the compiler that helps us to write less code, makes it looks like we are passing a function as a parameter.</p><p>Ok, lets take a look at the below sample for advantage #2!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bf81ddc7de788530ac0612bc86e7f9c/href">https://medium.com/media/0bf81ddc7de788530ac0612bc86e7f9c/href</a></iframe><p>In the example above, we transform the arraylist to a stream(<strong>this concept of stream is not the InputStream or OutputSteam from Java</strong>), and modify the stream by applying different operators. We first map every element from the stream(which is a stream of Integer object) by add 1, then filter out those Integer which are less than 10, then eventually we take only the first 10 elements from the stream. Noted that every time we apply an operator, we ”create” a new stream, and thats why we can apply those operators in a chain.</p><p>But wait, whats the advantage of having such a weird structure ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*RBFwLCiQ0G1aypbqhZxVbA.png" /></figure><p>I already mentioned that in functional programming language , we aim to not have “states” and just focus on the result of function execution.</p><p>For example we have a sequence of execution of functions :</p><p>funcA() -&gt; funB() -&gt;funcC();</p><p>In this case, funC() only handle the result from funcB(), and it will not use result from funcA(), this is the most ideal scenario for functional programming. Does it sounds silly? I bet thats what you wanna ask and this requirement seems not “advanced” right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*N1TcWNYwID3AbvUf_mBiFA.jpeg" /><figcaption>are you kidding me?</figcaption></figure><p>But just think about it, I believe most of the us have done something like this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65697756410bde82150e034eadf5f78d/href">https://medium.com/media/65697756410bde82150e034eadf5f78d/href</a></iframe><p>in the example , we use a global variable to control the execution of C(), but the variable is mutable and it has been changed in A()! So even though the sequence of the functions are A()-&gt;B()-&gt;C(), C() is not relied purely on B(), and thats against the rule of functional programming.</p><p>Maybe we can change a little bit of the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a82cb0e69be59e3059c9c27f72657998/href">https://medium.com/media/a82cb0e69be59e3059c9c27f72657998/href</a></iframe><p>This is much better now ! , B() and C() don’t rely on any global variable anymore, the executions of B() and C() are now purely decided by its own parameters.</p><p>Or we can make it even more “RxJava” like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22d027b6030f95fa2d1137683919e696/href">https://medium.com/media/22d027b6030f95fa2d1137683919e696/href</a></iframe><p>the code above demonstrates how we can make it more functional like !</p><p>But the question is -&gt; we still have a boolean flag in Exe class ! Isnt that against the rule of functional programming?</p><p>Well, thats not true, always remember, we dont want mutable variable to take control of the execution of our methods chain , thats true. But it doesn’t mean that we can’t use global variables. In the code above, every time we fire A() , B() or C(), we return a new instance of class Exe, we are not sharing the same instance of Exe along the way, which means only the last instance of Exe will control the execution of the current method calls.</p><p>So lets review Java 8 Stream API again , those operators like map(), filter(), limit() will create a new “Stream” and pass to the next operator call. You can always just modify the stream generated by the last operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dd106f92568927081741f3fbd064dc3/href">https://medium.com/media/1dd106f92568927081741f3fbd064dc3/href</a></iframe><p>So thats it for part 1, in the next post im gonna go through some operators and API from RxJava.</p><p>Here’s the link for the next post :</p><p><a href="https://medium.com/@qingzhong/rxjava-for-100-beginners-part-2-write-your-code-in-a-more-elegant-way-ccadfe61bb81">https://medium.com/@qingzhong/rxjava-for-100-beginners-part-2-write-your-code-in-a-more-elegant-way-ccadfe61bb81</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ab9081f2a34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>