AsynchronousIo

trait AsynchronousIo[+Value] extends Trait

The base keyword to perform asynchronous IO in domains.task.Tasks.

Example:

The following readAll is a Task to read file content with the help of AsynchronousIo.ReadFile

         import java.nio._, file._, channels._
         import com.thoughtworks.dsl.domains.Task
         import com.thoughtworks.dsl.keywords._
         import com.thoughtworks.dsl.keywords.Shift._
         import com.thoughtworks.dsl.keywords.AsynchronousIo.ReadFile
         import scala.collection.mutable.ArrayBuffer
         import scala.io.Codec
         def readAll(channel: AsynchronousFileChannel, temporaryBufferSize: Int = 4096): Task[ArrayBuffer[CharBuffer]] = Task {
           val charBuffers = ArrayBuffer.empty[CharBuffer]
           val decoder = Codec.UTF8.decoder
           val byteBuffer = ByteBuffer.allocate(temporaryBufferSize)
           var position: Long = 0L
           while (!ReadFile(channel, byteBuffer, position) != -1) {
             position += byteBuffer.position()
             byteBuffer.flip()
             charBuffers += decoder.decode(byteBuffer)
             byteBuffer.clear()
           }
           charBuffers
         }

Tasks created from !-notation can be used in for-comprehension, and other keywords can be used together in the same for block. For example, the following cat function contains a single for block to concatenate file contents. It asynchronously iterates elements Seq, ArrayBuffer and String with the help of keywords.Each, managed native resources with the help of keywords.Using, performs previously created readAll task with the help of keywords.Shift, and finally converts the return type as a Task[Vector[Char]].

         import com.thoughtworks.dsl._
         import com.thoughtworks.dsl.keywords._
         import com.thoughtworks.dsl.domains.Task
         import java.net.URL
         def cat(paths: Path*) = Each.ToView {
           for {
             path <- Each(paths)
             channel <- Using(AsynchronousFileChannel.open(path))
             charBuffers <- Shift(readAll(channel))
             charBuffer <- Each(charBuffers)
             char <- Each(charBuffer.toString)
           } yield char
         }.to[Task]

Then the cat function is used to concatenate files from this project, as shown below:

         Task.toFuture(Task {
           val filesToRead = for (fileName <- Seq(".sbtopts", ".scalafmt.conf")) yield {
             Paths.get(sourcecode.File()).getParent.resolve("../../../../../..").resolve(fileName)
           }
           (!Shift(cat(filesToRead: _*))).mkString should be(
             filesToRead.map { fileToRead =>
               new String(Files.readAllBytes(fileToRead), io.Codec.UTF8.charSet)
             }.mkString
           )
         })
Companion:
object
trait Trait
class Any
class Accept
class Connect
class Read
class ReadFile
class Write
class WriteFile