<?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 MobiTV on Medium]]></title>
        <description><![CDATA[Stories by MobiTV on Medium]]></description>
        <link>https://medium.com/@mobitv?source=rss-2240745c1dd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HmOtH7ajdg7oQDjpdospnw.png</url>
            <title>Stories by MobiTV on Medium</title>
            <link>https://medium.com/@mobitv?source=rss-2240745c1dd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:18:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mobitv/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[Go at MobiTV]]></title>
            <link>https://medium.com/@mobitv/go-at-mobitv-ed1b732f0dcf?source=rss-2240745c1dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed1b732f0dcf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[mobitv]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[MobiTV]]></dc:creator>
            <pubDate>Thu, 19 Mar 2020 02:42:38 GMT</pubDate>
            <atom:updated>2020-03-19T16:20:09.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7eGRkTK9dcy11V-TAjmtA.jpeg" /></figure><p>By: Rohit Korrapolu, Engineering Manager at, <a href="http://mobitv.com/">MobiTV</a></p><h3>Go, the Language Programmers Want</h3><p>Go is a procedural open-source language that was created at Google. It operates on the tenets of simplicity, reliability, and efficiency.</p><p>It was designed to replace the older system programming languages like C or C++ that are fast, yet inflexible and overly complicated. Because of that, there’s a lack of leading experts with the skillset necessary to master these languages, making it difficult to debug and get things right.</p><p>With Go, Google created a fresh new look and incorporated a lot of freestyle and functional programming concepts into the language. They revamped antiquated systems and created a trendy developer experience.</p><p>That said, C, C++, and similar languages are the crux of many operating systems. These object-oriented languages power many platforms including Windows, Linux, Unix, and Mac. But, their strength in power lends to an overly complicated, time-consuming design.</p><p>Go, on the other hand, takes a straightforward, top-down approach to programming. It was developed with powerful concurrency concepts that allow developers to leverage multiple CPU and OS-level interactions, giving them the capability to handle several requests simultaneously. This competency is challenging with other languages.</p><p>At MobiTV, we began working with Go two years ago because it is a fast programming language that allows us to streamline our engineering processes. It doesn’t require a VM like JVM for Java but rather it compiles to a single binary that can work across a multitude of platforms, unlike RUST, which is also gaining popularity.</p><h3>Ready Compiler</h3><p>The ability to compile to a single binary is unprecedented. This allows us to easily ship our code to all operating systems (Mac, Linux, and Windows) and put it to work immediately. The capability to ship and function seamlessly across all operating systems is vital as our clients utilize all three operating systems within their businesses.</p><p>As many of our infrastructure components were manual, our focus was to upgrade to an improved automated process. Go works on a majority of operating systems, and it offers several functional concepts, it really helps us to develop automation tools easily and quickly.</p><p>The more that we used Go, the more we realized its powerful capabilities. Not only is it incredibly easy for our developers to write code, but the standard library is powerful and effective. We began by working on infrastructure projects and once we realized success with those, we invested a lot more energy into building tools around the Go platform.</p><h3>Parallelize with Ease</h3><p>Go’s concurrency concepts, or channels, allows us to parallelize and compartmentalize many parts of our projects. For example, if we needed to access more than 250 projects, in a manual system we’d have to download them sequentially which would take approximately 20 minutes. With Go, we can pull the projects through Bitbucket at record speeds within a minute.</p><p>Go has also helped us to quickly circumvent outage issues that would otherwise take far longer to tackle on manual systems. During a recent outage, for example, we were able to write a small and simple program in Go in less than an hour and get it deployed within a day. That pace is groundbreaking. If we had to write that fix in Java or another language, it would have taken at least a week.</p><p>Since then, all of the new brand new media components are using the Go programming language.</p><h3>Development Made Simple</h3><p>As another point of comparison, Java, for example, has bulky software that requires a lot of testing. It is full of various components and a lot of boilerplate code. Go is intrinsically minimalistic. It only has about 500 lines of source code and we can easily use their robust built-in standard library. When working with Java, you have to navigate several external libraries that complicate the process.</p><p>Go, therefore, allows for seamless cross-team interaction and generates simplified collective productivity. It has performed 10x than the existing Java program and requires far less footprint. We can support twice the capacity with Go than we can with Java, at a decreased cost. Put simply, it is better code quality.</p><p>We’re also working to develop a new web portal for engineers with Go. This will enhance our ability to research, debug and analyze issues on our platform. This portal makes use of all of the microservice concepts that Go offers which gives us the ability to easily write and deploy services.</p><p>In terms of performance, Go has allowed us to significantly increase our development speeds. We’ve updated all of our command-line utilities in Go to provision our infrastructure.</p><h3>Enhanced Production Capabilities</h3><p>As an example of our enhanced production capabilities, our SRE/RE teams usually work on infrastructure automation for which Go is a good candidate. This means that all of the interns working with these teams can jump right into projects with little to no elucidation required. Their work in writing programs in Go to facilitate our developers on the SRE/RE teams not only expedites their programming speeds but helps us to collectively get things done faster across the board.</p><p>To better visualize how prodigious Go programming is, picture a brand new city. At first, it may only have a few buildings to serve its few residents. Because there’s a small demand in a modest space, these buildings can easily fulfill the needs of the people in the immediate surrounding area.</p><p>As the population grows, however, the people will begin to spread out across a larger area. That means that roads will need to be built so that goods and services can be transported to outlying clusters.</p><p>Go’s channels act as these roads. And each programmer can be taught how to safely and simply drive a car without any trouble. Where other languages may have roadblocks that create a traffic jam and must call in experts to find another route to their destination, Go’s channels allow cars to seamlessly move in a straight line without any unforeseen issues. And if an obstacle does arise, each car operator will be able to circumvent the jam without needing to consult a specialist.</p><p>Today, Go is the primary language that MobiTV developers are using, across both new and existing projects. We plan on cascading this language across the entire engineering organization within MobiTV in the near future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed1b732f0dcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MobiTV’s Kepler — A ML based capacity prediction system]]></title>
            <link>https://medium.com/@mobitv/mobitvs-kepler-a-ml-based-capacity-prediction-system-30d39f7ec39b?source=rss-2240745c1dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/30d39f7ec39b</guid>
            <category><![CDATA[forecasting]]></category>
            <category><![CDATA[capacity-planning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[MobiTV]]></dc:creator>
            <pubDate>Sat, 15 Feb 2020 00:23:38 GMT</pubDate>
            <atom:updated>2020-03-19T03:13:08.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kepler — A ML based capacity prediction system</h3><p>Author(s): Nick Dhupia and Rachit Singh — Engineering at MobiTV</p><p>At MobiTV, our business relies on meeting and exceeding strong demands for availability and reliability for applications used by our customers to watch live streaming content. MobiTV’s multi-tenant platform serves live video and VOD traffic to our customers on a variety of devices and platforms over hls and dash streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rj_YGNy_Sj4cVH6L" /></figure><p>MobiTV’s data centers contain hundreds of servers that deliver content to our customers. In the past, we predicted server capacity using spreadsheet models using data obtained by running performance and stress tests on staging environments. While such models are valuable, the method for obtaining data is time-consuming, error-prone and not scalable beyond a few teams. We needed a deterministic way to forecast server capacity and associated costs based on the expected user growth, new user features and software efficiencies over time.</p><p>Consequently, we built a tool (Kepler) that predicts the computing resources needed to support our explosive growth. Kepler does this by running ML algorithms on real-time performance data obtained using our production monitoring systems such as Dynatrace, Prometheus, Elk, Icinga, Datadog, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQ8_XiBYschW-41Tt78hFg.png" /><figcaption>Kepler Architecture</figcaption></figure><p>Kepler takes user input parameters such as desired CPU utilization for scaling, cache hit ratios, and number of subscribers.</p><p>Here is a screenshot for some of the inputs to Kepler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/0*ic6-PaP62lSZdyuA" /></figure><p>We store real-time metrics on a NoSql db (Cassandra) and run various ML models on the collected data on a nightly schedule. The results of the models are cached so that the Kepler is able to serve the prediction results quickly.</p><p>The graphs below summarizes the results of running a regression model generated using the tool for our Media Muxer nodes. Media Muxers are responsible for serving live and vod streams in a variety output formats such as dash, hlsv3, hlsv4, fmp4 and SmoothStreaming. Note that Kepler shows a significant correlation (correlation coefficient: 0.98) between CPU and Transaction per second for Media Muxer nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*PMQVGhkICrfP1bZl" /></figure><p>Kepler can dynamically choose the best fit ML model based on the node type, distribution of the data and results of rmse value seen during a run. We used the following chart to try out various ML algorithms for use in Kepler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rUM98mL0apq90Bz4" /><figcaption>Credit: <a href="https://scikit-learn.org/">https://scikit-learn.org/</a></figcaption></figure><p><strong>1. Linear Regression:</strong> It finds the optimal fit equation using the least squares method. Due to significant correlation between metrics — CPU usage and transaction per second, we’re using this model to predict future transactions and nodes based on current subscribers, and CPU usage.</p><p><strong>2.</strong> <strong>Polynomial Regression:</strong> Polynomial regression is useful only if there were non-linear relationships between the variables. However, we observed that none of our services manifest this relationship so we did not use polynomial regression. Note that using polynomial regression with degree &gt; 1, will result in overfitting and is not recommended.</p><p><strong>3.</strong> <strong>Stochastic Gradient Descent: </strong>Keeping Linear Regression as the base model, we implemented minimization through stochastic gradient descent. We observed that method provides a decent alternative to regression however we do observe higher rmse at times. In future, we might try out alternatives such as Batch Gradient Descent with optimizers like Momentum, RMSProp and Adam, which are used to overcome convergence problems around local and global minima as well as pathological curvature.</p><p><strong>4. Random Forest: </strong>This is a robust non-parametric predictor because it constructs large number of uncorrelated tree models which train on random slices of train cases. This injects randomness that makes them very accurate regressors. For capacity prediction scenarios, we often want to predict CPU required for TPS values we have not yet seen in the production environment. We observed that the Random Forest algorithm performs poorly for values it has not yet seen. We chose not to use evaluate algorithms like Random Forest, and LightGBM for our current use case.</p><p><strong>5. Support Vector Regression:</strong> A support vector regression algorithm attempts to create a function that keeps the target result within a threshold. This is slightly different from linear regression which tries to create a function that minimizes the error by using sum of least squares. SVR tends to be computationally expensive, however since we value recency of our data more than its volume, SVR works well for us in predicting capacity.</p><p>The following table showing the root mean squared error (rmse) values for the various model’s test cases. Note that the rmse values are almost similar for all of them. To calculate rmse, we split 30 days worth of data ingested with hourly granularity into training and test set. Models were fitted on the training set and rmse values were calculated using the test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*PW331iroF16QmAiNQ9Q3WQ.png" /><figcaption>rmse values for various models/services</figcaption></figure><p>The chart below shows results from predicting CPU for given TPS. Tree based model like Random Forest perform poorly as expected while the regression functions provide similar results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKW8wJ8M8ItceXO-" /></figure><p>The chart below depicts predicted TPS for a given CPU utilization % for Service A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*ACze0Ol8ZDImzeu-LbqHyQ.png" /></figure><p>So far, we have only predicted TPS (y-axis) given desired CPU (x-axis), however in practice we want to predict nodes/cores/pods given the rise in the number of subscribers to our video platform. For simplicity, let’s assume that for Service A, a percentage increase in subscribers results in similar percentage increase in TPS. Given this assumption, we utilize the following heuristic:</p><p><strong>Total Desired TPS</strong> = 90th percentile of TPS for Service A per node * current nodes * (1 + % rise in subscribers)</p><p><strong>Predicted TPS Per Node </strong>for a desired CPU utilization is derived using the ML models above</p><p>Now, we can easily extrapolate:</p><p><strong>Number of Desired Nodes</strong> = Total Desired TPS / Predicted TPS per Node</p><p>Finally, here is a chart that shows Kepler forecasting a 370, 100 and 266 percent rise for nodes running Service A, B and C respectively with SVR model - given a 1000% percent rise in number of subscribers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*nYaPRnfAKUT-rMDCb-1BPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2JcxzL4t2h4Tb_C-" /><figcaption>The future is already here, and it has changed jobs. Better take notice. Cartoon credit: TimoElliott.com</figcaption></figure><p>Much like astrology, Kepler favors correlation so long as the predictions are accurate. Kepler does this using large data and ML models based on the workload patterns observed on our servers. While a majority of servers show high correlation between user driven metrics like throughput, others are more correlated to latency and response sizes.</p><p>We have only begun to scratch the surface in terms of capacity planning and prediction and are actively looking for candidates who can help us solve difficult problems no matter if you are into astrology, have inclination towards Artificial Intelligence or simply love our taco Fridays.</p><p>Please visit our<a href="https://workforcenow.adp.com/mascsr/default/mdf/recruitment/recruitment.html?cid=71dd0c1a-07d5-420d-9344-7f7868fcd9f5&amp;ccId=19000101_000001&amp;type=MP&amp;lang=en_US&amp;selectedMenuKey=CurrentOpenings"> jobs</a> page for more information or email us your resume directly for consideration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30d39f7ec39b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LUS Fiber Wins with On-Campus Streaming TV]]></title>
            <link>https://medium.com/@mobitv/lus-fiber-wins-with-on-campus-streaming-tv-63f1554671b7?source=rss-2240745c1dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/63f1554671b7</guid>
            <category><![CDATA[customer-spotlight]]></category>
            <category><![CDATA[on-campus]]></category>
            <category><![CDATA[streaming-tv-service]]></category>
            <category><![CDATA[mobitv]]></category>
            <category><![CDATA[pay-tv]]></category>
            <dc:creator><![CDATA[MobiTV]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 17:24:35 GMT</pubDate>
            <atom:updated>2020-01-28T20:29:44.756Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>MobiTV Customer Spotlight</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fgZ2HUYP-LOgp7myn3vsUQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Habits are hard to break, especially on a large scale. The familiarity and reliability of a TV service that works can make the idea of upgrading to a modern streaming platform feel like a risky endeavor.</p><p>If the new system fails, it could be devastating as both costs and reputation are on the line. And with several competent emerging smart technologies on the market, it can be difficult to know which one is best for your venture.</p><p>This is especially true with large ventures like universities. Luckily, LUS Fiber, founded in 2009 was able to help a large Louisiana University commit to a full systems overhaul with confidence.</p><p>The university, housing around 3,500 students, had been using the same hard-line TV cable connection for years and paying a high price for it. As the competition increased and pressure mounted, the university felt it was time to make a change.</p><p><em>“Some of the other apartments they were competing with were pushing the ‘smart home, smart tech’ initiative, so the university began to consider ‘how do we differentiate ourselves from being just regular student housing, with the same old technology’”</em> says Ryan Meche, Engineering Manager at LUS Fiber.</p><p>In an effort to set themselves apart, they met with Meche from LUS Fiber and began having talks about how they could benefit from a streaming video service backed by MobiTV’s robust platform.</p><p>Meche told the university about the benefits of a live and on-demand, branded TV package ripe with sophisticated features.</p><p><em>“The students can not only watch in their room, but the service can expand to anywhere on campus,” </em>Meche explained.<em> “If they were in the library or in between classes, they could catch up on their recordings from wherever they were located.”</em></p><p>The university liked what they were hearing, but wanted some hard data to help assist with their difficult decision. They decided to conduct a study of how many of their student housing rooms had TV sets in them.</p><p>The results showed that while 30% of the rooms had TV sets, the students were consuming the majority of their video on streaming platforms. This is something that Meche and the team at LUS Fiber predicted as it aligns with current societal trends.</p><p>Meche explained how LUS Fiber’s partnership with MobiTV would afford the university with a purely unique and customizable video experience. The students would be given exclusive access to both streaming and smart cable TV with tons of distinctive amenities and features.</p><p><em>“So we presented our platform as the solution to the university’s problems of ‘how do we deliver this customized package, give the students the freedom and flexibility to view video the way that they’re used to and give them something unique that they wouldn’t have if they weren’t in the student housing program,’” </em>Meche said.</p><p>And it worked. Once LUS Fiber won the deal, they made sure it would stick. They went the extra mile to be present at student check-in and explain the ins and outs of the new video service. Even the parents loved it!</p><p><em>“The parents thought it was sharp and some of them were like, man, can I have access to this, this is a really cool product.”</em></p><p>The success of this effort was achieved with the extra help from the LUS engineering team that went above and beyond to work with the University to stress test the network and make sure all of the university’s concerns we addressed.</p><p>Once they got the student accounts set up, they began a widespread education effort to ensure it was successfully adopted and understood by both the students and the university alike. Meche and his team were tasked with explaining to students that they could choose from a suite of premium add-ons to enhance their viewing experience.</p><p>The response was incredibly positive, and they’re just getting started.</p><p>Soon, students will be able to log into their university’s very own branded local university video service app. This will add a personalized touch and be a huge selling point for the university as their video services will truly become a part of its branded suite of offerings.</p><p>Moreover, since the university launched its new streaming TV platform, nearby off-campus apartment complexes have been inquiring about how to get a piece of the pie. They’ve heard the great reviews and want to know more.</p><p><em>“So since the launch, we’ve actually had other apartment complexes being like look, we heard you have the special smart home, the streaming application, how can we get in on it?”</em></p><p>The success at the university has not only extended to off-campus apartments, but Meche says they hope this is the start of something new for their brand presence in the city. As students graduate, many will stay in the area and, thus, already be familiar with their service. Because of this, there’s a high chance they’ll purchase their own LUS Fiber service post-grad.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63f1554671b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simplified Guide to Kotlin Coroutines]]></title>
            <link>https://medium.com/@mobitv/a-simplified-guide-to-kotlin-coroutines-edc9149ad54f?source=rss-2240745c1dd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/edc9149ad54f</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[MobiTV]]></dc:creator>
            <pubDate>Thu, 16 Jan 2020 17:30:18 GMT</pubDate>
            <atom:updated>2020-01-16T18:53:08.987Z</atom:updated>
            <content:encoded><![CDATA[<p>By: <a href="https://www.linkedin.com/in/daniel-medeiros-1483b54/">Daniel Medeiros</a>, Sr. Lead Software Engineer/Application Architect at <a href="http://mobitv.com/">MobiTV</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_G2b6944OqV9qTXae59UA.jpeg" /></figure><h3>Intro</h3><p>There’s a lot to grok when it comes to Kotlin Coroutines. If you haven’t already used a similar concept in another language, getting started can be confusing.</p><p>I’ve found that the introductory IntelliJ <a href="https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html">documentation</a> about this great feature goes into surprisingly mind-numbing detail. The following is my attempt at distilling this information down to the basics you need to understand in order to get started with coroutines.</p><p>Note that this is just a basic guide. I don’t go into structured concurrency (an important concept which you should definitely wrap your head around once you’ve got the basics down). Job cancellation, runBlocking, continuations, mutexes/semaphores, and ViewModel coroutine scope on Android Jetpack — to name just a few things — are all important features as well. Hopefully, after you’ve read this, the Kotlin Coroutines Guide will make more sense and you can research these other topics.</p><h3>What is a Coroutine?</h3><p>As you’ve likely read elsewhere, a coroutine in Kotlin is like a lightweight thread. Very lightweight. So lightweight, in fact, that if you were to run thousands of them at the same time you would not significantly affect the performance of your application.</p><p>Unlike threads though, coroutines are easy to manage. You don’t have to manage a thread pool yourself. Canceling a coroutine (“interrupting” in thread parlance) is simple and straightforward. Typically, Kotlin’s coroutine library handles the maintenance of dependent coroutine lifecycles for you through the use of scopes (which I will go into later).</p><p>Coroutines make your code easier to understand as well. Starting a coroutine is simple and elegant. You don’t have to keep track of nested callbacks for asynchronous operations, thereby avoiding the <a href="https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)">Pyramid of Doom</a>. Your code is written in a straightforward, sequential manner that looks synchronous but is actually executing asynchronous code while not blocking any underlying threads.</p><h3>How it works</h3><p>Kotlin manages this amazing feat by making opportunistic use of discrete thread pools associated with each coroutine dispatcher. A coroutine can *<em>suspend</em>* at any given point — essentially yielding control to any other coroutine(s) that run in the same thread pool — and later (once the return from the preempting coroutine is available, for example) *<em>resume</em>* on any available thread.</p><p>This does mean that coroutines can jump threads. But it’s not something you need to care about — you can just focus on the work you need your coroutine to do, and leave scheduling concerns up to the dispatcher.</p><h3>Suspend and Resume</h3><p>To declare code that must run inside of a coroutine, Kotlin offers the <strong>suspend </strong>keyword:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79fd832528bf82e162e44cb0a042990b/href">https://medium.com/media/79fd832528bf82e162e44cb0a042990b/href</a></iframe><p>The <strong>suspend</strong> keyword indicates to Kotlin that at some point the logic will cause the currently running coroutine to suspend, yielding control to another coroutine. In the example above, the suspension point occurs in <strong>delay</strong>: this function suspends the coroutine for a specified amount of time — in this case, five seconds.</p><p>At some point after the work done by the suspending function is complete, the coroutine resumes.</p><p>Output:</p><pre>start of waitSomeTime()</pre><pre>end of waitSomeTime() 5008ms later</pre><p>What’s nice about the above is it can run concurrently with executions on the main thread. The call to <strong>delay</strong> <em>does not block</em> — it only suspends the coroutine and allows the main thread to go about its business processing other events, such as frame draw. Once the timeout is up, the coroutine would resume and finish its business logic.</p><h3>Dispatchers</h3><p>What if I have a call that does some I/O? This is not an appropriate thing to do from the main thread (particularly on platforms like Android), and it’s not a suspending function (I/O blocks, it does not suspend). How would get the work off of the main thread while taking advantage of the suspending feature of coroutines?</p><p>All coroutines are associated with a dispatcher which specifies how to run the code inside of the coroutine. One of the dispatchers provided by the core coroutines package is <strong>Dispatchers.IO</strong> — this allows you to specify that a block of code should run on a thread pool dedicated to I/O operations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b6557a290223b07a34bc88c44d84f22/href">https://medium.com/media/8b6557a290223b07a34bc88c44d84f22/href</a></iframe><p>Here we call <strong>withContext(Dispatchers.IO)</strong> to tell Kotlin to suspend the coroutine until it runs <strong>someIO</strong> on the I/O thread pool and has the call response. When <strong>someIO</strong> returns, our coroutine resumes and we can handle the response appropriately.</p><p>Other dispatchers are provided out of the box by the kotlinx-coroutines-core package:</p><ul><li><strong>Dispatchers.Default </strong>— the dispatcher used by default whenever a coroutine is launched. It is backed by a shared pool of threads.</li><li><strong>Dispatchers.Main </strong>— this dispatcher runs coroutines on the main thread (generally responsible for updating the UI). While a coroutine is suspended, the main thread is free to go about processing other tasks in its event loop.</li><li><strong>Dispatchers.Unconfined</strong> — this dispatcher allows you to say that you don’t care what thread pool the coroutine is associated with. A suspended function may resume on a thread other than the one that made the initial call, and execution will simply continue on the new thread.</li></ul><h3>Starting a Coroutine</h3><p>You’ve written your coroutine logic — now how do you get it running?</p><p>If you just call a suspend function from non-suspend code you’ll get a compiler error. You have to launch the coroutine first before you can execute its suspending function.</p><p>To do this you need to launch from within a scope. Scope, in this case, works similarly to block scopes: the coroutine lasts only for as long as the scope is valid. When the scope terminates, any coroutines running within that scope are canceled.</p><p>There are two scopes provided by the kotlinx-coroutines-core package:</p><ul><li><strong>MainScope </strong>— this scope starts things out on the main thread</li><li><strong>GlobalScope </strong>— this scope lasts the lifetime of an application. This is the top level scope.</li></ul><p>You can create your own scopes nested within the above scopes by calling <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html">coroutineScope</a> from within a coroutine.</p><p>On Android Jetpack, the <a href="https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope">lifecycleScope</a> property lets you define scopes associated with the lifecycle of a specific activity or fragment. When the fragment or activity is destroyed, the scope ends and any running coroutines are canceled.</p><p>Once you’ve decided on a scope to run in, you can launch a coroutine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5531e740dd8bf2533093d411d8418e11/href">https://medium.com/media/5531e740dd8bf2533093d411d8418e11/href</a></iframe><p>Note that <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html">launch</a> is a fire-and-forget function. It just starts a new coroutine and leaves it at that (note that a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html">Job</a> instance is returned if you’d like to cancel the coroutine while it’s running). No return value can be retrieved from the coroutine.</p><p>If you do want a return value, then use <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html">async</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb5ec982303a0b3265b3cf678fe89a5d/href">https://medium.com/media/cb5ec982303a0b3265b3cf678fe89a5d/href</a></iframe><h3>A Beefier Example</h3><p>Let’s take a look at a simple example of making an asynchronous call and receiving its result, first using the “classic” multi-threaded approach. Afterward, we’ll do the same thing using coroutines. Both of these examples will be in Kotlin.</p><p>Imagine we have an Android app providing an Amazon-like storefront that needs to promote a featured product every day. Our job is to retrieve the product’s details and display them to the user. We have one REST API (“GET /featuredProduct”) to get the product’s ID and we have a generic REST API to get the details of any product we want, based on its ID (“GET /productDetails”).</p><p>Our application uses Retrofit in league with OkHttp2 in order to abstract away a lot of the details involved in making the required REST requests</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ce5c47ac7ce2e0455441dfa6f62c3e9/href">https://medium.com/media/6ce5c47ac7ce2e0455441dfa6f62c3e9/href</a></iframe><p>Here’s one approach to asynchronously making this series of REST requests using callbacks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1327fca0f50919a82958bac3366a3d05/href">https://medium.com/media/1327fca0f50919a82958bac3366a3d05/href</a></iframe><p>This is not very elegant at all. We seem to be approaching the Pyramid of Doom.</p><ul><li>Line 6: make an asynchronous call to get the featured product’s ID using Retrofit’s Call.enqueue() API. We have to pass a callback to get the response.</li><li>Line 11: When the onResponse callback occurs we make another nested call to get the product details</li><li>Line 10: Finally we have the product detail and we can display it to the user</li></ul><p>Not shown: code to deal with errors, how to indicate to the user that an async request is occurring, and how to cancel this task if the user decides to back out of the activity before it’s done. In short, the above can require a lot of supporting code and it can all get pretty messy. The cognitive load required to understand and maintain this code rises sharply.</p><p>One could make the argument that we could write this call sequence more cleanly using an RxJava chain. But there would still be some nesting and a long call chain involved, not to mention the stack requirements to execute a long RxJava chain.</p><p>Coroutines offer a better way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/050a669a6f4d07c3edf5120999dca9e4/href">https://medium.com/media/050a669a6f4d07c3edf5120999dca9e4/href</a></iframe><p>Assuming we call this function from the main thread:</p><ul><li>Line 5: Make a synchronous call to get the featured product’s ID using Retrofit’s Call.execute() method.</li><li>— withContext(Dispatchers.IO) specifies that this code should be run on the <strong>IO dispatcher</strong>, which uses a designated thread pool to execute the code off of the main thread.</li><li>— While the code is running on the IO dispatcher, the currently running coroutine is <strong>suspended</strong>. The main thread is not blocked during this time and is allowed to process other tasks.</li><li>Line 6: If an error occurs, we handle it immediately (perhaps showing an error to the user) and just return.</li><li>Line 13: Using the response from the last call we make another synchronous call to get the product’s details. Again, we use <strong>withContext (Dispatchers.IO)</strong> to suspend the coroutine while this is going on.</li><li>Line 20: Show the product’s detail to the user. Here we use the main dispatcher since this is a UI operation.</li></ul><p>Much easier to follow and less boilerplate. Very little nesting — everything is left aligned. You can follow the execution of the business logic sequentially, even though we have to asynchronously request data off of the main thread.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edc9149ad54f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>