Search in sources :

Example 11 with Action0

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);
}
Also used : MockResponse(com.google.mockwebserver.MockResponse) Action0(rx.functions.Action0) HttpResourceGroup(com.netflix.ribbon.http.HttpResourceGroup) AtomicReference(java.util.concurrent.atomic.AtomicReference) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) HystrixBadRequestException(com.netflix.hystrix.exception.HystrixBadRequestException) HttpClientResponse(io.reactivex.netty.protocol.http.client.HttpClientResponse) MockWebServer(com.google.mockwebserver.MockWebServer) Test(org.junit.Test)

Example 12 with Action0

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;
}
Also used : Action0(rx.functions.Action0) CompositeException(rx.exceptions.CompositeException) ArrayList(java.util.ArrayList) Observable(rx.Observable) Func1(rx.functions.Func1)

Example 13 with Action0

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));
}
Also used : Completable(rx.Completable) Action0(rx.functions.Action0) Func1(rx.functions.Func1) Queue(com.microsoft.azure.management.servicebus.Queue)

Example 14 with Action0

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();
        }
    });
}
Also used : Action0(rx.functions.Action0) User(me.jessyan.mvparms.demo.mvp.model.entity.User) ArrayList(java.util.ArrayList) List(java.util.List) RetryWithDelay(me.jessyan.rxerrorhandler.handler.RetryWithDelay) PermissionUtil(com.jess.arms.utils.PermissionUtil)

Example 15 with Action0

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");
        }
    });
}
Also used : Action0(rx.functions.Action0) ProgressDialog(android.app.ProgressDialog) InjectView(butterknife.InjectView) HorizontalScrollView(android.widget.HorizontalScrollView) View(android.view.View) TextPointView(com.wingjay.jianshi.ui.widget.TextPointView) MultipleRowTextView(com.wingjay.jianshi.ui.widget.MultipleRowTextView) TextView(android.widget.TextView) ScrollView(android.widget.ScrollView) ShareContent(com.wingjay.jianshi.bean.ShareContent) Func1(rx.functions.Func1) File(java.io.File) Pair(android.util.Pair) OnClick(butterknife.OnClick)

Aggregations

Action0 (rx.functions.Action0)134 Subscription (rx.Subscription)58 Test (org.junit.Test)56 CountDownLatch (java.util.concurrent.CountDownLatch)50 Action1 (rx.functions.Action1)28 AtomicReference (java.util.concurrent.atomic.AtomicReference)23 ArrayList (java.util.ArrayList)16 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)16 List (java.util.List)15 Func1 (rx.functions.Func1)13 HystrixRuntimeException (com.netflix.hystrix.exception.HystrixRuntimeException)12 Observable (rx.Observable)12 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 OnClick (butterknife.OnClick)10 IOException (java.io.IOException)9 CommandStreamTest (com.netflix.hystrix.metric.CommandStreamTest)8 UiThreadTest (android.support.test.annotation.UiThreadTest)7 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)7 TestCollapserTimer (com.netflix.hystrix.HystrixCollapserTest.TestCollapserTimer)7 Method (java.lang.reflect.Method)7