Plug and play code samples for Reactive Extensions.
This page aims to provide real world examples of the usage of RxJava/RxAndroid. Feel free to submit a pull request for other samples.
public interface MyRetrofitService {
@GET("/locations")
Observable<Location> getLocation();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://example.com")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
MyRetrofitService retrofitService = retrofit.create(MyRetrofitService.class);
Observable.interval(3000, TimeUnit.MILLISECONDS)
.flatMap(param -> retrofitService.getLocation())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<Location>() {
@Override
public void onCompleted() {
Log.d("api", "rx comleted");
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Location location) {
Log.d("api", "response: " + location.getSomeField());
}
});
private Subscription mSubscription;
mSubscription = RxTextView.textChangeEvents(mSearchField)
.debounce(600, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<TextViewTextChangeEvent>() {
@Override
public void onCompleted() {
Log.d(TAG, "onCompleted() called");
}
@Override
public void onError(Throwable e) {
}
//Called every time theres a text change and then a pause for at least 600ms.
@Override
public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
mSearchOutput.setText("Searched for: " + textViewTextChangeEvent.text());
}
});
public Observable<Object> rxflattenmylist(List<?> list) {
return Observable.from(list)
.flatMap(item -> item instanceof List<?> ? rxflattenmylist((List<?>) item) : Observable.just(item));
}
public Observable<List<Object>> rxflatten(List<Object> list) {
return rxflattenmylist(list)
.toList();
}