Created
November 1, 2014 20:00
-
-
Save tschulte/76e6ef2193c318f6a2bc to your computer and use it in GitHub Desktop.
Automatically show progress of rxjava Observable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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