Skip to content

Instantly share code, notes, and snippets.

@OlivierBlanvillain
Created March 23, 2017 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OlivierBlanvillain/4105d05aea258b56f9317b3c81072118 to your computer and use it in GitHub Desktop.
Save OlivierBlanvillain/4105d05aea258b56f9317b3c81072118 to your computer and use it in GitHub Desktop.
Monix based Ajax
object Ajax {
def get(url: String, data: InputData = null, timeout: Int = 0,
headers: Map[String, String] = Map.empty,
withCredentials: Boolean = false, responseType: String = "") = {
apply("GET", url, data, timeout, headers, withCredentials, responseType)
}
def post(url: String, data: InputData = null, timeout: Int = 0,
headers: Map[String, String] = Map.empty,
withCredentials: Boolean = false, responseType: String = "") = {
apply("POST", url, data, timeout, headers, withCredentials, responseType)
}
def apply(
method: String,
url: String,
data: InputData,
timeout: Int,
headers: Map[String, String],
withCredentials: Boolean,
responseType: String
): Task[dom.XMLHttpRequest] = {
Task.create[dom.XMLHttpRequest] {
case (s: Scheduler, c: Callback[dom.XMLHttpRequest]) =>
val req = new dom.XMLHttpRequest()
req.onreadystatechange = { (e: dom.Event) =>
if (req.readyState.toInt == 4) {
if ((req.status >= 200 && req.status < 300) || req.status == 304)
c.onSuccess(req)
else
c.onError(AjaxException(req))
}
}
req.open(method, url)
req.responseType = responseType
req.timeout = timeout
req.withCredentials = withCredentials
headers.foreach(x => req.setRequestHeader(x._1, x._2))
if (data == null)
req.send()
else
req.send(data)
def onSuccess(value: T): Unit
def onError(ex: Throwable): Unit
monix.Cancelable.empty
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment