Search in sources :

Example 31 with Flowable

use of io.reactivex.Flowable in project Rocket.Chat.Android by RocketChat.

the class DDPClientImpl method connect.

public void connect(final TaskCompletionSource<DDPClientCallback.Connect> task, final String url, String session) {
    try {
        flowable = websocket.connect(url).autoConnect();
        CompositeDisposable subscriptions = new CompositeDisposable();
        subscriptions.add(flowable.filter(callback -> callback instanceof RxWebSocketCallback.Open).subscribe(callback -> {
            sendMessage("connect", json -> (TextUtils.isEmpty(session) ? json : json.put("session", session)).put("version", "pre2").put("support", new JSONArray().put("pre2").put("pre1")), task);
        }, err -> {
        }));
        subscriptions.add(flowable.filter(callback -> callback instanceof RxWebSocketCallback.Message).map(callback -> ((RxWebSocketCallback.Message) callback).responseBodyString).map(DDPClientImpl::toJson).timeout(7, TimeUnit.SECONDS).subscribe(response -> {
            String msg = extractMsg(response);
            if ("connected".equals(msg) && !response.isNull("session")) {
                task.trySetResult(new DDPClientCallback.Connect(client, response.optString("session")));
                subscriptions.dispose();
            } else if ("error".equals(msg) && "Already connected".equals(response.optString("reason"))) {
                task.trySetResult(new DDPClientCallback.Connect(client, null));
                subscriptions.dispose();
            } else if ("failed".equals(msg)) {
                task.trySetError(new DDPClientCallback.Connect.Failed(client, response.optString("version")));
                subscriptions.dispose();
            }
        }, err -> task.trySetError(new DDPClientCallback.Connect.Timeout(client))));
        addErrorCallback(subscriptions, task);
        subscribeBaseListeners();
    } catch (Exception e) {
        RCLog.e(e);
    }
}
Also used : RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) TimeoutException(java.util.concurrent.TimeoutException) TextUtils(android.text.TextUtils) NonNull(android.support.annotation.NonNull) RCLog(chat.rocket.android.log.RCLog) TaskCompletionSource(bolts.TaskCompletionSource) TimeUnit(java.util.concurrent.TimeUnit) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) JSONException(org.json.JSONException) RxWebSocket(chat.rocket.android_ddp.rx.RxWebSocket) JSONObject(org.json.JSONObject) OkHttpClient(okhttp3.OkHttpClient) Flowable(io.reactivex.Flowable) Nullable(android.support.annotation.Nullable) Task(bolts.Task) JSONArray(org.json.JSONArray) JSONArray(org.json.JSONArray) RxWebSocketCallback(chat.rocket.android_ddp.rx.RxWebSocketCallback) TimeoutException(java.util.concurrent.TimeoutException) JSONException(org.json.JSONException) CompositeDisposable(io.reactivex.disposables.CompositeDisposable)

Example 32 with Flowable

use of io.reactivex.Flowable in project rxjava2-jdbc by davidmoten.

the class NonBlockingPool method createMembers.

private Flowable<Member<T>> createMembers() {
    List<Member<T>> ms = IntStream.range(1, maxSize + 1).mapToObj(//
    n -> memberFactory.create(NonBlockingPool.this)).collect(Collectors.toList());
    Flowable<Member<T>> baseMembers = //
    Flowable.fromIterable(ms).doOnRequest(n -> log.debug("requested={}", n));
    Flowable<Member<T>> returnedMembers = //
    subject.toSerialized().toFlowable(BackpressureStrategy.BUFFER);
    // use CAS loop to handle a race with close
    while (true) {
        List<Member<T>> l = list.get();
        if (l == null) {
            return Flowable.error(new PoolClosedException());
        } else if (list.compareAndSet(Collections.emptyList(), ms)) {
            return //
            returnedMembers.doOnNext(//
            m -> log.debug("returned member reentering")).mergeWith(//
            baseMembers).doOnNext(//
            x -> log.debug("member={}", x)).<Member<T>>flatMap(member -> member.checkout().toFlowable(), false, //
            1).doOnNext(x -> log.debug("checked out member={}", x));
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) BackpressureStrategy(io.reactivex.BackpressureStrategy) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Preconditions(com.github.davidmoten.guavamini.Preconditions) Callable(java.util.concurrent.Callable) Predicate(io.reactivex.functions.Predicate) AtomicReference(java.util.concurrent.atomic.AtomicReference) Collectors(java.util.stream.Collectors) Consumer(io.reactivex.functions.Consumer) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Scheduler(io.reactivex.Scheduler) Flowable(io.reactivex.Flowable) PublishSubject(io.reactivex.subjects.PublishSubject) PoolClosedException(org.davidmoten.rx.jdbc.pool.PoolClosedException) Schedulers(io.reactivex.schedulers.Schedulers) Collections(java.util.Collections) PoolClosedException(org.davidmoten.rx.jdbc.pool.PoolClosedException)

Example 33 with Flowable

use of io.reactivex.Flowable in project todo-mvp-rxjava by albertizzy.

the class TasksPresenter method loadTasks.

/**
 * @param forceUpdate   Pass in true to refresh the data in the {@link TasksDataSource}
 * @param showLoadingUI Pass in true to display a loading icon in the UI
 */
private void loadTasks(final boolean forceUpdate, final boolean showLoadingUI) {
    if (showLoadingUI) {
        mTasksView.setLoadingIndicator(true);
    }
    if (forceUpdate) {
        mTasksRepository.refreshTasks();
    }
    // The network request might be handled in a different thread so make sure Espresso knows
    // that the app is busy until the response is handled.
    // App is busy until further notice
    EspressoIdlingResource.increment();
    mCompositeDisposable.clear();
    Disposable disposable = mTasksRepository.getTasks().flatMap(Flowable::fromIterable).filter(task -> {
        switch(mCurrentFiltering) {
            case ACTIVE_TASKS:
                return task.isActive();
            case COMPLETED_TASKS:
                return task.isCompleted();
            case ALL_TASKS:
            default:
                return true;
        }
    }).toList().subscribeOn(mSchedulerProvider.io()).observeOn(mSchedulerProvider.ui()).doFinally(() -> {
        if (!EspressoIdlingResource.getIdlingResource().isIdleNow()) {
            // Set app as idle.
            EspressoIdlingResource.decrement();
        }
    }).subscribe(// onNext
    tasks -> {
        processTasks(tasks);
        mTasksView.setLoadingIndicator(false);
    }, // onError
    throwable -> mTasksView.showLoadingTasksError());
    mCompositeDisposable.add(disposable);
}
Also used : CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) TasksDataSource(com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource) BaseSchedulerProvider(com.example.android.architecture.blueprints.todoapp.util.schedulers.BaseSchedulerProvider) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) NonNull(android.support.annotation.NonNull) EspressoIdlingResource(com.example.android.architecture.blueprints.todoapp.util.EspressoIdlingResource) TasksRepository(com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository) List(java.util.List) CompositeDisposable(io.reactivex.disposables.CompositeDisposable) Disposable(io.reactivex.disposables.Disposable) Flowable(io.reactivex.Flowable) AddEditTaskActivity(com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskActivity) Activity(android.app.Activity) Task(com.example.android.architecture.blueprints.todoapp.data.Task) Flowable(io.reactivex.Flowable)

Example 34 with Flowable

use of io.reactivex.Flowable in project cxf by apache.

the class JAXRSRxJava2FlowableTest method testGetHelloWorldEmpty2.

@Test
public void testGetHelloWorldEmpty2() throws Exception {
    String address = "http://localhost:" + PORT + "/rx22/flowable/empty";
    final Flowable<Response> obs = ClientBuilder.newClient().register(new JacksonJsonProvider()).register(new FlowableRxInvokerProvider()).target(address).request(MediaType.APPLICATION_JSON).rx(FlowableRxInvoker.class).get();
    final TestSubscriber<Response> subscriber = new TestSubscriber<>();
    obs.subscribe(subscriber);
    subscriber.await(3, TimeUnit.SECONDS);
    subscriber.assertValue(r -> "[]".equals(r.readEntity(String.class))).assertComplete();
}
Also used : Response(javax.ws.rs.core.Response) FlowableRxInvokerProvider(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider) BeforeClass(org.junit.BeforeClass) WebClient(org.apache.cxf.jaxrs.client.WebClient) Assert.assertTrue(org.junit.Assert.assertTrue) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Test(org.junit.Test) Invocation(javax.ws.rs.client.Invocation) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) NotFoundException(javax.ws.rs.NotFoundException) TimeUnit(java.util.concurrent.TimeUnit) GenericType(javax.ws.rs.core.GenericType) ClientBuilder(javax.ws.rs.client.ClientBuilder) AbstractResourceInfo(org.apache.cxf.jaxrs.model.AbstractResourceInfo) List(java.util.List) MediaType(javax.ws.rs.core.MediaType) Response(javax.ws.rs.core.Response) Flowable(io.reactivex.Flowable) AbstractBusClientServerTestBase(org.apache.cxf.testutil.common.AbstractBusClientServerTestBase) FlowableRxInvoker(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker) TestSubscriber(io.reactivex.subscribers.TestSubscriber) LinkedList(java.util.LinkedList) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) FlowableRxInvokerProvider(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) FlowableRxInvoker(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker) TestSubscriber(io.reactivex.subscribers.TestSubscriber) Test(org.junit.Test)

Example 35 with Flowable

use of io.reactivex.Flowable in project cxf by apache.

the class JAXRSRxJava2FlowableTest method testFlowableImmediateErrorsWithExceptionMapper.

@Test
public void testFlowableImmediateErrorsWithExceptionMapper() throws Exception {
    String address = "http://localhost:" + PORT + "/rx22/flowable/immediate/mapper/errors";
    final Flowable<Response> obs = ClientBuilder.newClient().register(new JacksonJsonProvider()).register(new FlowableRxInvokerProvider()).target(address).request(MediaType.APPLICATION_JSON).rx(FlowableRxInvoker.class).get();
    final TestSubscriber<Response> subscriber = new TestSubscriber<>();
    obs.subscribe(subscriber);
    subscriber.await(3, TimeUnit.SECONDS);
    subscriber.assertValue(r -> r.getStatus() == 409 && r.readEntity(String.class).contains("stackTrace")).assertComplete();
}
Also used : Response(javax.ws.rs.core.Response) FlowableRxInvokerProvider(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider) BeforeClass(org.junit.BeforeClass) WebClient(org.apache.cxf.jaxrs.client.WebClient) Assert.assertTrue(org.junit.Assert.assertTrue) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Test(org.junit.Test) Invocation(javax.ws.rs.client.Invocation) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) NotFoundException(javax.ws.rs.NotFoundException) TimeUnit(java.util.concurrent.TimeUnit) GenericType(javax.ws.rs.core.GenericType) ClientBuilder(javax.ws.rs.client.ClientBuilder) AbstractResourceInfo(org.apache.cxf.jaxrs.model.AbstractResourceInfo) List(java.util.List) MediaType(javax.ws.rs.core.MediaType) Response(javax.ws.rs.core.Response) Flowable(io.reactivex.Flowable) AbstractBusClientServerTestBase(org.apache.cxf.testutil.common.AbstractBusClientServerTestBase) FlowableRxInvoker(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker) TestSubscriber(io.reactivex.subscribers.TestSubscriber) LinkedList(java.util.LinkedList) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) FlowableRxInvokerProvider(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) FlowableRxInvoker(org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker) TestSubscriber(io.reactivex.subscribers.TestSubscriber) Test(org.junit.Test)

Aggregations

Flowable (io.reactivex.Flowable)65 Test (org.junit.Test)29 List (java.util.List)21 TimeUnit (java.util.concurrent.TimeUnit)19 Observable (io.reactivex.Observable)14 TestSubscriber (io.reactivex.subscribers.TestSubscriber)14 Assert.assertTrue (org.junit.Assert.assertTrue)14 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)13 Single (io.reactivex.Single)13 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)13 ClientBuilder (javax.ws.rs.client.ClientBuilder)13 MediaType (javax.ws.rs.core.MediaType)13 AbstractResourceInfo (org.apache.cxf.jaxrs.model.AbstractResourceInfo)13 FlowableRxInvoker (org.apache.cxf.jaxrs.rx2.client.FlowableRxInvoker)13 FlowableRxInvokerProvider (org.apache.cxf.jaxrs.rx2.client.FlowableRxInvokerProvider)13 AbstractBusClientServerTestBase (org.apache.cxf.testutil.common.AbstractBusClientServerTestBase)13 BeforeClass (org.junit.BeforeClass)13 Collections (java.util.Collections)9 Response (javax.ws.rs.core.Response)9 Assert.assertEquals (org.junit.Assert.assertEquals)9