-
java callback 을 scala Future 로 바꾸기scala/basic 2022. 7. 16. 18:57
문제
다음과 같이 java Async Http Client 의 callback 을 scala Future 로 변경해 코딩해 보자
val asyncHttpClient = org.asynchttpclient.Dsl.asyncHttpClient() val listenableFuture = asyncHttpClient.prepareGet("https://api.agify.io/?name=meelad").execute() val listener = new Runnable { override def run(): Unit = { val body: String = listenableFuture.get().getResponseBody(scala.io.Codec.UTF8.charSet) println(body) } } listenableFuture.addListener(listener, null) Thread.sleep(3000) asyncHttpClient.close()
코드
import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.{Future, Promise} val p = Promise[String] val asyncHttpClient = org.asynchttpclient.Dsl.asyncHttpClient() val listenableFuture = asyncHttpClient.prepareGet("https://api.agify.io/?name=meelad").execute() listenableFuture.addListener( () => { val body: String = listenableFuture.get().getResponseBody(scala.io.Codec.UTF8.charSet) p.success(body) }, null ) val scalaFuture: Future[String] = p.future scalaFuture.foreach(println) Thread.sleep(3000) asyncHttpClient.close()
설명
java callback 을 ZIO 로 바꾸는 것도 가능한데, https://wefree.tistory.com/200 를 참고
'scala > basic' 카테고리의 다른 글
F-Bound (0) 2022.11.12 Scala Closure (0) 2022.10.21 sealed trait typeclass (0) 2022.03.29 scala 에서 retry 구현하기 (0) 2021.11.25 scala enumeratum enum 사용하기 (0) 2021.11.13