Sunday, May 3, 2020

Kotlin - Coroutines


Some tasks are best performed in the background. So Coroutines let you write code that's run asynchronously. Coroutines allow you to create multiple pieces of code that run asynchronously. Instead of running pieces of code in sequence one after another, Coroutines let you run them side-by-side.

To add a Coroutine dependency in your project you have to add this:

dependencies
{
  compile 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
  implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.0.1'
}

A Coroutine is like a lightweight thread 

Behind the scenes, launching a Coroutine is like starting a separate thread of execution or thread. The key difference, however, is that it is more efficient to use Coroutines in your code than it is to use threads.
Starting a thread and keeping it running is quite expensive in terms of performance. Coroutines run on a shared pool of threads by default and the same thread can run many coroutines. As fewer threads are used this makes it more efficient to use Coroutines when you want to run tasks asynchronously.

So let's create a sample code that runs in parallel. So I will play sound files run in separate coroutines in the same thread.

Code Example:  

import java.io.File

import javax.sound.sampled.AudioSystem

import kotlinx.coroutines.*



//Why Suspend because it van call the delay function

suspend fun playBeats(beats:String,file:string)

{

   val parts = beats.split("x")

   var count = 0

   for(parts in parts)

    {
        count + = parts.lenght + 1

        if(part == "")

        {

           playSound(file)

        }
else
{
  delay(100 * (part.length + 1L))
  if(count < beats.length)
  {
    playSound(file)
  }
}

   }
 
   fun playSound(file : String)
   {
     val clip = AudioSystem.getClip()
     val audioInputStream = AudioSystem.getAudioInputStream(
            File(
file
)
)
     clip.open()
clip.start()
   }

suspend fun main()
{
           runBlocking
   {
     launch
{
   playBeats("some file name","abc.aiff")
}

   }
}

}

When you run the code, it plays the some music in parallel, and the sound file run in separate coroutines in the same thread.

Some Important Points:

  • coroutines let you run code asynchronously . They are useful for running background tasks.
  • A coroutine is like a lightweight thread. Coroutine run on the shared pool of threads by default and the same thread can run many coroutines.
  • Use the launch function to launch a new coroutine.
  • The runBlocking function blocks the current thread until the code it contains has finished running.
  • The delay function suspends the code for a specified length of time. It can be used inside a coroutine or inside a function that's marked using suspend.







1 comment:

Anonymous said...

Can you please write more problem and share.