suspend fundoSomething() {
// do something as asynchronous processingprintln("Process has done!")
}
funmain() {
doSomething() // This causes an error because it isn't called in a coroutine scope
}
/* Error Message: * Suspend function 'doSomething' should be called only from a coroutine or another suspend function */
import kotlinx.coroutines.*
suspend fundoSomething() {
// do something as asynchronous processingdelay(2_000L)
println("Process has done!")
}
funmain() {
runBlocking { // Starting the coroutine scopelaunch { // Building the new coroutinedoSomething()
}
println("Hello!")
}
}
/* Outputs: * Hello! * Process has done! * */
suspend fundownloadFile(): Boolean {
try {
// Simulating a download process with a delaydelay(5_000L)
returntrue// Assuming the download is successful
} catch (e: CancellationException) {
// Handling the case where the process is cancelledprintln("The download has been cancelled by the user.")
throw e // Rethrowing the cancellation event
}
}
println("Starting the download.")
valjob = launch {
isDownloaded = downloadFile() // Executing the download
}
// Waiting a bit before cancelling the jobdelay(1_000L) // Waiting for the download to startjob.cancelAndJoin() // Cancelling the job and waiting for its completion (assuming it's cancelled by the user)
import kotlinx.coroutines.*
varisDownloaded = false// Initially assuming the download is not completed (false)suspend fundownloadFile(): Boolean {
try {
// Simulating a download process with a delaydelay(5_000L)
returntrue// Assuming the download is successful
} catch (e: CancellationException) {
// Handling the case where the process is cancelledprintln("The download has been cancelled by the user.")
throw e // Rethrowing the cancellation event
}
}
funmain() {
runBlocking { // Starting the coroutine scopeprintln("Starting the download.")
valjob = launch {
isDownloaded = downloadFile() // Executing the download
}
// Waiting a bit before cancelling the jobdelay(1_000L) // Waiting for the download to startjob.cancelAndJoin() // Cancelling the job and waiting for its completion (assuming it's cancelled by the user)
}
// Displaying the final message about the download statusif(isDownloaded) {
println("The download has completed successfully.")
} else {
println("The download has not completed.")
}
println("Download status: $isDownloaded")
}
このコードを実行すると、まず、println によって “Starting the download.” の文字列が出力されます。