use of rx.functions.Action0 in project ribbon by Netflix.
the class RibbonTest method testValidator.
@Test
public void testValidator() throws IOException, InterruptedException {
// LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
MockWebServer server = new MockWebServer();
String content = "Hello world";
server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-type", "text/plain").setBody(content));
server.play();
HttpResourceGroup group = Ribbon.createHttpResourceGroup("myclient", ClientOptions.create().withConfigurationBasedServerList("localhost:" + server.getPort()));
HttpRequestTemplate<ByteBuf> template = group.newTemplateBuilder("test", ByteBuf.class).withUriTemplate("/").withMethod("GET").withResponseValidator(new ResponseValidator<HttpClientResponse<ByteBuf>>() {
@Override
public void validate(HttpClientResponse<ByteBuf> t1) throws UnsuccessfulResponseException {
throw new UnsuccessfulResponseException("error", new IllegalArgumentException());
}
}).build();
RibbonRequest<ByteBuf> request = template.requestBuilder().build();
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
request.toObservable().subscribe(new Action1<ByteBuf>() {
@Override
public void call(ByteBuf t1) {
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable t1) {
error.set(t1);
latch.countDown();
}
}, new Action0() {
@Override
public void call() {
}
});
latch.await();
assertTrue(error.get() instanceof HystrixBadRequestException);
assertTrue(error.get().getCause() instanceof UnsuccessfulResponseException);
}
use of rx.functions.Action0 in project azure-sdk-for-java by Azure.
the class ExternalChildResourceCollectionImpl method commitAsync.
/**
* Commits the changes in the external child resource childCollection.
* <p/>
* This method returns an observable stream, its observer's onNext will be called for each successfully
* committed resource followed by one call to 'onCompleted' or one call to 'onError' with a
* {@link CompositeException } containing the list of exceptions where each exception describes the reason
* for failure of a resource commit.
*
* @return the observable stream
*/
public Observable<FluentModelTImpl> commitAsync() {
final ExternalChildResourceCollectionImpl<FluentModelTImpl, FluentModelT, InnerModelT, ParentImplT, ParentT> self = this;
List<FluentModelTImpl> items = new ArrayList<>();
for (FluentModelTImpl item : this.childCollection.values()) {
items.add(item);
}
final List<Throwable> exceptionsList = Collections.synchronizedList(new ArrayList<Throwable>());
Observable<FluentModelTImpl> deleteStream = Observable.from(items).filter(new Func1<FluentModelTImpl, Boolean>() {
@Override
public Boolean call(FluentModelTImpl childResource) {
return childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeRemoved;
}
}).flatMap(new Func1<FluentModelTImpl, Observable<FluentModelTImpl>>() {
@Override
public Observable<FluentModelTImpl> call(final FluentModelTImpl childResource) {
return childResource.deleteAsync().map(new Func1<Void, FluentModelTImpl>() {
@Override
public FluentModelTImpl call(Void response) {
return childResource;
}
}).doOnNext(new Action1<FluentModelTImpl>() {
@Override
public void call(FluentModelTImpl childResource) {
childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None);
self.childCollection.remove(childResource.name());
}
}).onErrorResumeNext(new Func1<Throwable, Observable<FluentModelTImpl>>() {
@Override
public Observable<FluentModelTImpl> call(Throwable throwable) {
exceptionsList.add(throwable);
return Observable.empty();
}
});
}
});
Observable<FluentModelTImpl> createStream = Observable.from(items).filter(new Func1<FluentModelTImpl, Boolean>() {
@Override
public Boolean call(FluentModelTImpl childResource) {
return childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeCreated;
}
}).flatMap(new Func1<FluentModelTImpl, Observable<FluentModelTImpl>>() {
@Override
public Observable<FluentModelTImpl> call(final FluentModelTImpl childResource) {
return childResource.createAsync().map(new Func1<FluentModelT, FluentModelTImpl>() {
@Override
public FluentModelTImpl call(FluentModelT fluentModelT) {
return childResource;
}
}).doOnNext(new Action1<FluentModelTImpl>() {
@Override
public void call(FluentModelTImpl fluentModelT) {
childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None);
}
}).onErrorResumeNext(new Func1<Throwable, Observable<? extends FluentModelTImpl>>() {
@Override
public Observable<FluentModelTImpl> call(Throwable throwable) {
self.childCollection.remove(childResource.name());
exceptionsList.add(throwable);
return Observable.empty();
}
});
}
});
Observable<FluentModelTImpl> updateStream = Observable.from(items).filter(new Func1<FluentModelTImpl, Boolean>() {
@Override
public Boolean call(FluentModelTImpl childResource) {
return childResource.pendingOperation() == ExternalChildResourceImpl.PendingOperation.ToBeUpdated;
}
}).flatMap(new Func1<FluentModelTImpl, Observable<FluentModelTImpl>>() {
@Override
public Observable<FluentModelTImpl> call(final FluentModelTImpl childResource) {
return childResource.updateAsync().map(new Func1<FluentModelT, FluentModelTImpl>() {
@Override
public FluentModelTImpl call(FluentModelT e) {
return childResource;
}
}).doOnNext(new Action1<FluentModelTImpl>() {
@Override
public void call(FluentModelTImpl childResource) {
childResource.setPendingOperation(ExternalChildResourceImpl.PendingOperation.None);
}
}).onErrorResumeNext(new Func1<Throwable, Observable<? extends FluentModelTImpl>>() {
@Override
public Observable<FluentModelTImpl> call(Throwable throwable) {
exceptionsList.add(throwable);
return Observable.empty();
}
});
}
});
final PublishSubject<FluentModelTImpl> aggregatedErrorStream = PublishSubject.create();
Observable<FluentModelTImpl> operationsStream = Observable.merge(deleteStream, createStream, updateStream).doOnTerminate(new Action0() {
@Override
public void call() {
if (clearAfterCommit()) {
self.childCollection.clear();
}
if (exceptionsList.isEmpty()) {
aggregatedErrorStream.onCompleted();
} else {
aggregatedErrorStream.onError(new CompositeException(exceptionsList));
}
}
});
Observable<FluentModelTImpl> stream = Observable.concat(operationsStream, aggregatedErrorStream);
return stream;
}
use of rx.functions.Action0 in project azure-sdk-for-java by Azure.
the class QueueImpl method createChildResourceAsync.
@Override
protected Observable<Queue> createChildResourceAsync() {
Completable createQueueCompletable = this.manager().inner().queues().createOrUpdateAsync(this.resourceGroupName(), this.parentName, this.name(), this.inner()).map(new Func1<QueueInner, QueueInner>() {
@Override
public QueueInner call(QueueInner inner) {
setInner(inner);
return inner;
}
}).toCompletable();
Completable childrenOperationsCompletable = submitChildrenOperationsAsync();
final Queue self = this;
return Completable.concat(createQueueCompletable, childrenOperationsCompletable).doOnTerminate(new Action0() {
@Override
public void call() {
initChildrenOperationsCache();
}
}).andThen(Observable.just(self));
}
use of rx.functions.Action0 in project MVPArms by JessYanCoding.
the class UserPresenter method requestUsers.
public void requestUsers(final boolean pullToRefresh) {
//请求外部存储权限用于适配android6.0的权限管理机制
PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
@Override
public void onRequestPermissionSuccess() {
//request permission success, do something.
}
}, mRootView.getRxPermissions(), mRootView, mErrorHandler);
//上拉刷新默认只请求第一页
if (pullToRefresh)
lastUserId = 1;
//关于RxCache缓存库的使用请参考 http://www.jianshu.com/p/b58ef6b0624b
//是否驱逐缓存,为ture即不使用缓存,每次上拉刷新即需要最新数据,则不使用缓存
boolean isEvictCache = pullToRefresh;
if (pullToRefresh && isFirst) {
//默认在第一次上拉刷新时使用缓存
isFirst = false;
isEvictCache = false;
}
mModel.getUsers(lastUserId, isEvictCache).subscribeOn(Schedulers.io()).retryWhen(//遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
new RetryWithDelay(3, 2)).doOnSubscribe(new Action0() {
@Override
public void call() {
if (pullToRefresh)
//显示上拉刷新的进度条
mRootView.showLoading();
else
//显示下拉加载更多的进度条
mRootView.startLoadMore();
}
}).subscribeOn(AndroidSchedulers.mainThread()).observeOn(AndroidSchedulers.mainThread()).doAfterTerminate(new Action0() {
@Override
public void call() {
if (pullToRefresh)
//隐藏上拉刷新的进度条
mRootView.hideLoading();
else
//隐藏下拉加载更多的进度条
mRootView.endLoadMore();
}
}).compose(//使用RXlifecycle,使subscription和activity一起销毁
RxUtils.<List<User>>bindToLifecycle(mRootView)).subscribe(new ErrorHandleSubscriber<List<User>>(mErrorHandler) {
@Override
public void onNext(List<User> users) {
//记录最后一个id,用于下一次请求
lastUserId = users.get(users.size() - 1).getId();
//如果是上拉刷新则清空列表
if (pullToRefresh)
mUsers.clear();
for (User user : users) {
mUsers.add(user);
}
//通知更新数据
mAdapter.notifyDataSetChanged();
}
});
}
use of rx.functions.Action0 in project jianshi by wingjay.
the class ViewActivity method share.
@OnClick(R.id.view_share)
void share() {
Blaster.log(LoggingData.BTN_CLK_SHARE_DIARY_IMAGE);
final View target = verticalStyle ? container : normalContainer;
final ProgressDialog dialog = ProgressDialog.show(this, "", "加载中...");
screenshotManager.shotScreen(target, "temp.jpg").observeOn(Schedulers.io()).filter(new Func1<String, Boolean>() {
@Override
public Boolean call(String s) {
return !TextUtils.isEmpty(s);
}
}).flatMap(new Func1<String, Observable<Pair<String, ShareContent>>>() {
@Override
public Observable<Pair<String, ShareContent>> call(String path) {
Timber.i("ViewActivity ScreenshotManager 1 %s", Thread.currentThread().getName());
ShareContent shareContent = new ShareContent();
try {
JsonDataResponse<ShareContent> response = userService.getShareContent().toBlocking().first();
if (response.getRc() == Constants.ServerResultCode.RESULT_OK && response.getData() != null) {
shareContent = response.getData();
}
} catch (Exception e) {
Timber.e(e, "getShareContent() error");
return Observable.just(Pair.create(path, shareContent));
}
return Observable.just(Pair.create(path, shareContent));
}
}).observeOn(AndroidSchedulers.mainThread()).doOnTerminate(new Action0() {
@Override
public void call() {
dialog.dismiss();
}
}).subscribe(new Action1<Pair<String, ShareContent>>() {
@Override
public void call(Pair<String, ShareContent> stringShareContentPair) {
Timber.i("ViewActivity ScreenshotManager 2 %s", Thread.currentThread().getName());
if (!isUISafe()) {
return;
}
IntentUtil.shareLinkWithImage(ViewActivity.this, stringShareContentPair.second, Uri.fromFile(new File(stringShareContentPair.first)));
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
makeToast(getString(R.string.share_failure));
Timber.e(throwable, "screenshot share failure");
}
});
}
Aggregations