Skip to content

Instantly share code, notes, and snippets.

@tschulte
Created November 1, 2014 20:00
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 tschulte/76e6ef2193c318f6a2bc to your computer and use it in GitHub Desktop.
Save tschulte/76e6ef2193c318f6a2bc to your computer and use it in GitHub Desktop.
Automatically show progress of rxjava Observable
@Grab('io.reactivex:rxjava:+')
@Grab('io.reactivex:rxswing:+')
import groovy.beans.Bindable
import groovy.swing.SwingBuilder
import rx.Observable
import rx.schedulers.*
import java.awt.BorderLayout
def sb = new SwingBuilder()
@Bindable
class BusyModel {
int progress
int max
String result = ''
public <T> Observable<T> busyWhile(Observable<T> observable, int numberOfExpectedItems) {
int incrementCount = 0
return observable
.doOnNext { progress++; incrementCount++ }
.doOnSubscribe { max += numberOfExpectedItems }
.doOnUnsubscribe { max -= numberOfExpectedItems; progress -= incrementCount }
}
}
def loadFromServer(int id) {
Thread.sleep(1000)
return id
}
def busyModel = new BusyModel()
sb.build {
frame(visible: true, title: 'progress-test', pack: true) {
borderLayout()
progressBar(constraints: BorderLayout.CENTER,
maximum: bind { busyModel.max },
value: bind { busyModel.progress }
)
textField(constraints: BorderLayout.SOUTH, text: bind { busyModel.result }, editable: false, columns: 50)
}
}
busyModel.busyWhile(Observable.from((1..10) as List)
.map { loadFromServer(it) }
.subscribeOn(Schedulers.io())
.observeOn(SwingScheduler.instance), 10)
.subscribe({ busyModel.result += it }, { e -> e.printStackrace() })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment