-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathAsyncWikiErrorHandling.scala
38 lines (35 loc) · 1.17 KB
/
AsyncWikiErrorHandling.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.net.URL
import java.util.Scanner
import rx.lang.scala.Observable
object AsyncWikiErrorHandling extends App {
/*
* Fetch a list of Wikipedia articles asynchronously, with error handling.
*/
def fetchWikipediaArticleAsynchronously(wikipediaArticleNames: String*): Observable[String] = {
Observable(subscriber => {
new Thread(new Runnable() {
def run(): Unit = {
try {
for (articleName <- wikipediaArticleNames) {
if (subscriber.isUnsubscribed) {
return
}
val url = "http://en.wikipedia.org/wiki/" + articleName
val art = new Scanner(new URL(url).openStream()).useDelimiter("\\A").next()
subscriber.onNext(art)
}
if (!subscriber.isUnsubscribed) {
subscriber.onCompleted()
}
} catch {
case t: Throwable => subscriber.onError(t)
}
}
}).start()
})
}
fetchWikipediaArticleAsynchronously("Tiger", "Elephant")
.subscribe(
art => println("--- Article ---\n" + art.substring(0, 125)),
e => println("--- Error ---\n" + e.getMessage) )
}