-
Notifications
You must be signed in to change notification settings - Fork 111
/
Copy pathAsyncObservable.scala
37 lines (35 loc) · 1.06 KB
/
AsyncObservable.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
import rx.lang.scala.Observable
object AsyncObservable extends App {
/**
* This example shows a custom Observable that does not block
* when subscribed to as it spawns a separate thread.
*/
def customObservableNonBlocking(): Observable[String] = {
Observable(
/*
* This 'call' method will be invoked when the Observable is subscribed to.
*
* It spawns a thread to do it asynchronously.
*/
subscriber => {
// For simplicity this example uses a Thread instead of an ExecutorService/ThreadPool
new Thread(new Runnable() {
def run(): Unit = {
for (i <- 0 to 75) {
if (subscriber.isUnsubscribed) {
return
}
subscriber.onNext("value_" + i)
}
// after sending all values we complete the sequence
if (!subscriber.isUnsubscribed) {
subscriber.onCompleted()
}
}
}).start()
}
)
}
// To see output:
customObservableNonBlocking().subscribe(println(_))
}