Created
June 23, 2020 14:22
-
-
Save reynoldsm88/1d991446b5c0734a54ee2a5091e167db to your computer and use it in GitHub Desktop.
Use Scala futures for async requests in okhttp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val client : OkHttpClient = new OkHttpClient.Builder().build() | |
val TEXT : MediaType = MediaType.get( "text/plain; charset=utf-8" ) | |
def asyncRequest( text : String ) : Future[ String ] = { | |
val body = RequestBody.create( text, TEXT ) | |
val request = new Request.Builder().url( "http://michael.com" ).post( body ).build() | |
val promise : Promise[ String ] = Promise[ String ]() | |
client.newCall( httpRequest ).enqueue( new Callback { | |
override def onFailure( call : Call, e : IOException ) : Unit = promise.failure( e ) | |
override def onResponse( call : Call, httpResponse : Response ) : Unit = promise.complete( Success( "yay!!!" ) ) | |
} ) | |
promse.future | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment