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.bangnotation._ import com.thoughtworks.dsl.comprehension._ 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.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 [[comprehension.ComprehensionOps.as as]] a `Task[Vector[Char]]`.
import com.thoughtworks.dsl._ import com.thoughtworks.dsl.bangnotation._ import com.thoughtworks.dsl.keywords._ import com.thoughtworks.dsl.keywords.Shift._ import com.thoughtworks.dsl.domains.Task import java.net.URL def cat(paths: Path*) = { for { path <- Each(paths) channel <- Using(AsynchronousFileChannel.open(path)) charBuffers <- Shift(readAll(channel)) charBuffer <- Each(charBuffers) char <- Each(charBuffer.toString) } yield char }.as[Task[Vector[Char]]]
Then the `cat` function is used to concatenate files from this project, as shown below:
Task.toFuture(*[Task] { (!Shift(cat(Paths.get(".sbtopts"), Paths.get(".scalafmt.conf")))).mkString should be( "-J-XX:MaxMetaspaceSize=512M\n-J-Xmx5G\n-J-Xss6M\nversion = \"1.5.1\"\nmaxColumn = 120" ) })
- Companion
- object