-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathAsyncWiki.scala
32 lines (29 loc) · 976 Bytes
/
AsyncWiki.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
import java.net.URL
import java.util.Scanner
import rx.lang.scala.Observable
object AsyncWiki extends App {
/*
* Fetch a list of Wikipedia articles asynchronously.
*/
def fetchWikipediaArticleAsynchronously(wikipediaArticleNames: String*): Observable[String] = {
Observable(subscriber => {
new Thread(new Runnable() {
def run(): Unit = {
for (articleName <- wikipediaArticleNames) {
if (subscriber.isUnsubscribed) {
return
}
val url = "https://en.wikipedia.org/wiki/" + articleName
val art = new Scanner(new URL(url).openStream()).useDelimiter("\\A").next()
subscriber.onNext(art)
}
if (!subscriber.isUnsubscribed) {
subscriber.onCompleted()
}
}
}).start()
})
}
fetchWikipediaArticleAsynchronously("Tiger", "Elephant")
.subscribe(art => println("--- Article ---\n" + art.substring(0, 125)))
}