我是coroutine和Kotlin的新学徒。 为什么我会得到不同的结果,下面的情况1和2?
import java.time.ZonedDateTime
import akka.actor.ActorSystem
import akka.stream.scaladsl.{MergeHub, Sink, Source}
import akka.stream.{ActorMaterializer, ActorMaterializerSettings, ThrottleMode}
import org.asynchttpclient.{DefaultAsyncHttpClient, _}
import scala.concurrent.duration._
import scala.concurrent.{Await, Future, Promise}
import scala.language.postfixOps
import scala.util.{Failure, Success, Try}
object Main {
private implicit val system = ActorSystem("root")
private implicit val executor = system.dispatcher
private implicit val mat = ActorMaterializer(ActorMaterializerSettings(system))
type PendingRequest = () => Future[Try[Response]]
private val throttlingSink =
MergeHub.source[PendingRequest]
.throttle(1, FiniteDuration(2000, MILLISECONDS), 1, ThrottleMode.Shaping)
.mapAsync(4)(_.apply())
.to(Sink.ignore)
.run()
def wrap(p: Promise[Try[Response]]): AsyncCompletionHandler[Response] = new AsyncCompletionHandler[Response] {
override def onThrowable(t: Throwable): Unit =
p.success(Failure(t))
override def onCompleted(response: Response): Response = {
p.success(Success(response))
response
}
}
def makeRequest(url: String): Future[Response] = {
val p = Promise[Try[Response]]
Source.single[PendingRequest](() => {
asyncHttpClient
.prepareGet(url)
.execute(wrap(p))
p.future
})
.runWith(throttlingSink)
p.future.flatMap {
case Success(r) => Future.successful(r)
case Failure(ex) => Future.failed(ex)
}
}
val asyncHttpClient = new DefaultAsyncHttpClient()
def main(args: Array[String]): Unit = {
val start = ZonedDateTime.now()
println("Start!")
Source(1 to 20)
.mapAsync(4) { index =>
println(s"${ZonedDateTime.now().toEpochSecond - start.toEpochSecond} s - Requesting $index")
makeRequest(s"https://httpbin.org/get?param=$index").map { r =>
println(s"${ZonedDateTime.now().toEpochSecond - start.toEpochSecond} s - Got $index - Code ${r.getStatusCode}")
}
}
.runWith(Sink.ignore)
.onComplete {
case Success(_) =>
println(s"${ZonedDateTime.now().toEpochSecond - start.toEpochSecond} Done!")
asyncHttpClient.close()
system.terminate()
case Failure(ex) =>
ex.printStackTrace()
asyncHttpClient.close()
system.terminate()
}
Await.result(system.whenTerminated, Duration.Inf)
}
}
这种val样式编码是基本的吗?
答案 0 :(得分:11)
案例1 等同于
val A = a()
await(A)
val B = b()
await(B)
也就是说,你开始A
,等待它(此处协程暂停),然后才开始B
,因此A
和B
按顺序执行,不是同时的。
在案例2 中,您同时启动A
和B
,然后协程才会暂停等待A
和B
。