Skip to content

Instantly share code, notes, and snippets.

@reynoldsm88
Created June 23, 2020 14:22
Show Gist options
  • Save reynoldsm88/1d991446b5c0734a54ee2a5091e167db to your computer and use it in GitHub Desktop.
Save reynoldsm88/1d991446b5c0734a54ee2a5091e167db to your computer and use it in GitHub Desktop.
Use Scala futures for async requests in okhttp
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