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.ReadFileimport 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 }
`Task`s 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.FromIterable]], 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 [[comprehension.ComprehensionOps.as as]] a `Task[Vector[Char]]`.
import com.thoughtworks.dsl._ import com.thoughtworks.dsl.keywords._ import com.thoughtworks.dsl.domains.Task import com.thoughtworks.dsl.Dsl.to import java.net.URL def cat(paths: Path*) = FromIterable.ToView { for { path <- FromIterable(paths) channel <- Using(AsynchronousFileChannel.open(path)) charBuffers <- Shift(readAll(channel)) charBuffer <- FromIterable(charBuffers) char <- FromIterable(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