Search in sources :

Example 1 with Flowable

use of io.reactivex.Flowable in project RxJava by ReactiveX.

the class BlockingFlowableToIteratorTest method overflowQueue.

@Test(expected = MissingBackpressureException.class)
public void overflowQueue() {
    Iterator<Integer> it = new Flowable<Integer>() {

        @Override
        protected void subscribeActual(Subscriber<? super Integer> s) {
            s.onSubscribe(new BooleanSubscription());
            s.onNext(1);
            s.onNext(2);
        }
    }.blockingIterable(1).iterator();
    it.next();
}
Also used : BooleanSubscription(io.reactivex.internal.subscriptions.BooleanSubscription) Flowable(io.reactivex.Flowable)

Example 2 with Flowable

use of io.reactivex.Flowable in project RxJava by ReactiveX.

the class FlowableMergeDelayErrorTest method mergeManyError.

@SuppressWarnings("unchecked")
@Test
@Ignore("No 2-9 parameter mergeDelayError() overloads")
public void mergeManyError() throws Exception {
    for (int i = 2; i < 10; i++) {
        Class<?>[] clazz = new Class[i];
        Arrays.fill(clazz, Flowable.class);
        Flowable<Integer>[] obs = new Flowable[i];
        for (int j = 0; j < i; j++) {
            obs[j] = withError(Flowable.just(1));
        }
        Integer[] expected = new Integer[i];
        Arrays.fill(expected, 1);
        Method m = Flowable.class.getMethod("mergeDelayError", clazz);
        TestSubscriber<Integer> ts = TestSubscriber.create();
        ((Flowable<Integer>) m.invoke(null, (Object[]) obs)).subscribe(ts);
        ts.assertValues(expected);
        ts.assertError(CompositeException.class);
        ts.assertNotComplete();
        CompositeException ce = (CompositeException) ts.errors().get(0);
        assertEquals(i, ce.getExceptions().size());
    }
}
Also used : Method(java.lang.reflect.Method) Flowable(io.reactivex.Flowable)

Example 3 with Flowable

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

the class BackpressureStrategyTest method testBackpressureBufferStrategy.

@Test
public void testBackpressureBufferStrategy() throws Exception {
    new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("timer:gen?period=20&repeatCount=20").setBody().header(Exchange.TIMER_COUNTER).to("reactive-streams:integers");
        }
    }.addRoutesToCamelContext(context);
    Flowable<Integer> integers = Flowable.fromPublisher(CamelReactiveStreams.get(context).fromStream("integers", Integer.class));
    ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
    CountDownLatch latch = new CountDownLatch(1);
    Flowable.interval(0, 50, TimeUnit.MILLISECONDS).zipWith(integers, (l, i) -> i).timeout(2000, TimeUnit.MILLISECONDS, Flowable.empty()).doOnComplete(latch::countDown).subscribe(queue::add);
    context().start();
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(20, queue.size());
    int num = 1;
    for (int i : queue) {
        assertEquals(num++, i);
    }
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) TestSubscriber(org.apache.camel.component.reactive.streams.support.TestSubscriber) CountDownLatch(java.util.concurrent.CountDownLatch) CamelReactiveStreams(org.apache.camel.component.reactive.streams.api.CamelReactiveStreams) Flowable(io.reactivex.Flowable) RouteBuilder(org.apache.camel.builder.RouteBuilder) Exchange(org.apache.camel.Exchange) Test(org.junit.Test) CamelTestSupport(org.apache.camel.test.junit4.CamelTestSupport) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) RouteBuilder(org.apache.camel.builder.RouteBuilder) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 4 with Flowable

use of io.reactivex.Flowable in project retrofit by square.

the class RxJava2CallAdapterFactoryTest method rawBodyTypeThrows.

@Test
public void rawBodyTypeThrows() {
    Type observableType = new TypeToken<Observable>() {
    }.getType();
    try {
        factory.get(observableType, NO_ANNOTATIONS, retrofit);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Observable return type must be parameterized as Observable<Foo> or Observable<? extends Foo>");
    }
    Type singleType = new TypeToken<Single>() {
    }.getType();
    try {
        factory.get(singleType, NO_ANNOTATIONS, retrofit);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Single return type must be parameterized as Single<Foo> or Single<? extends Foo>");
    }
    Type maybeType = new TypeToken<Maybe>() {
    }.getType();
    try {
        factory.get(maybeType, NO_ANNOTATIONS, retrofit);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Maybe return type must be parameterized as Maybe<Foo> or Maybe<? extends Foo>");
    }
    Type flowableType = new TypeToken<Flowable>() {
    }.getType();
    try {
        factory.get(flowableType, NO_ANNOTATIONS, retrofit);
        fail();
    } catch (IllegalStateException e) {
        assertThat(e).hasMessage("Flowable return type must be parameterized as Flowable<Foo> or Flowable<? extends Foo>");
    }
}
Also used : Type(java.lang.reflect.Type) Maybe(io.reactivex.Maybe) Single(io.reactivex.Single) Observable(io.reactivex.Observable) Flowable(io.reactivex.Flowable) Test(org.junit.Test)

Example 5 with Flowable

use of io.reactivex.Flowable in project GitTest by xiaoxige.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    testView = (TestView) findViewById(R.id.testView);
    testView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            MainActivityPermissionsDispatcher.showCameraWithPermissionCheck(MainActivity.this);
        }
    });
    try {
        ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        String appMV = appInfo.metaData.getString("MTA_CHANNEL");
        Toast.makeText(MainActivity.this, "appMV = " + appMV, Toast.LENGTH_SHORT).show();
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    simpleDraweeView = (SimpleDraweeView) findViewById(R.id.simpleDraweeView);
    testView.setProgress(100, false);
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            testView.setProgress(3, true);
        }
    }, 2000);
    GenericDraweeHierarchy hierarchy = simpleDraweeView.getHierarchy();
    RoundingParams roundingParams = new RoundingParams();
    roundingParams.setBorder(Color.RED, 10);
    roundingParams.setRoundAsCircle(true);
    hierarchy.setRoundingParams(roundingParams);
    simpleDraweeView.setHierarchy(hierarchy);
    ControllerListener listener = new BaseControllerListener() {

        @Override
        public void onFinalImageSet(String id, @Nullable Object imageInfo, @Nullable Animatable animatable) {
            super.onFinalImageSet(id, imageInfo, animatable);
        }
    };
    DraweeController controller = Fresco.newDraweeControllerBuilder().setUri(new Uri.Builder().scheme(UriUtil.LOCAL_RESOURCE_SCHEME).path(String.valueOf(R.mipmap.ic_launcher)).build()).setOldController(simpleDraweeView.getController()).setControllerListener(listener).build();
    simpleDraweeView.setController(controller);
    /**
     * 网络相关(retrofit+rxjava+rxlife+stetho)
     */
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(5000, TimeUnit.SECONDS).readTimeout(5000, TimeUnit.SECONDS).writeTimeout(5000, TimeUnit.SECONDS).addNetworkInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Headers headers = request.headers();
            Headers build = headers.newBuilder().add("version", "1.0").add("token", "xiaoxige").build();
            request = request.newBuilder().headers(build).build();
            Log.e("TAG", "url = " + request.url().uri().toString());
            String method = request.method();
            if (method.equals("GET") || method.equals("DELETE")) {
                HttpUrl url = request.url();
                HttpUrl httpUrl = url.newBuilder().addQueryParameter("xiaoxige", "one").addQueryParameter("zhuxiaoan", "two").build();
                request = request.newBuilder().url(httpUrl).build();
            } else {
                RequestBody body = request.body();
                if (body != null) {
                    Buffer buffer = new Buffer();
                    body.writeTo(buffer);
                    String readUtf8 = buffer.readUtf8();
                    // 可能需要对body进行加密
                    // TODO: 2017/11/3
                    RequestBody requestBody = RequestBody.create(body.contentType(), readUtf8);
                    request = request.newBuilder().method(method, requestBody).build();
                }
            }
            return chain.proceed(request);
        }
    }).addNetworkInterceptor(new StethoInterceptor()).build();
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.baidu.com").addConverterFactory(ScalarsConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).client(client).build();
    final NetApi api = retrofit.create(NetApi.class);
    Flowable flowable = Flowable.create(new FlowableOnSubscribe<String>() {

        @Override
        public void subscribe(@NonNull FlowableEmitter<String> flowableEmitter) throws Exception {
            String response = MainActivity.execute(api.getBaiduWeb());
            if (TextUtils.isEmpty(response)) {
                flowableEmitter.onError(new Exception());
                return;
            }
            flowableEmitter.onNext(response);
            flowableEmitter.onComplete();
        }
    }, BackpressureStrategy.LATEST).compose(bindUntilEvent(ActivityEvent.DESTROY)).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io());
    flowable.subscribe(new XXGSubscriber<String>() {

        @Override
        public void xxgNext(String o) {
            super.xxgNext(o);
            Log.e("TAG", "o = " + o);
        }

        @Override
        public void xxgError(Throwable t) {
            super.xxgError(t);
            Log.e("TAG", "t = " + t.getMessage());
        }

        @Override
        public void xxgComplete() {
            super.xxgComplete();
            Log.e("TAG", "Complete");
        }
    });
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GenericDraweeHierarchy(com.facebook.drawee.generic.GenericDraweeHierarchy) DraweeController(com.facebook.drawee.interfaces.DraweeController) Headers(okhttp3.Headers) ApplicationInfo(android.content.pm.ApplicationInfo) Uri(android.net.Uri) PackageManager(android.content.pm.PackageManager) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) NonNull(io.reactivex.annotations.NonNull) FlowableEmitter(io.reactivex.FlowableEmitter) Interceptor(okhttp3.Interceptor) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) RoundingParams(com.facebook.drawee.generic.RoundingParams) RequestBody(okhttp3.RequestBody) Buffer(okio.Buffer) FlowableOnSubscribe(io.reactivex.FlowableOnSubscribe) Request(okhttp3.Request) Handler(android.os.Handler) ControllerListener(com.facebook.drawee.controller.ControllerListener) BaseControllerListener(com.facebook.drawee.controller.BaseControllerListener) IOException(java.io.IOException) SimpleDraweeView(com.facebook.drawee.view.SimpleDraweeView) View(android.view.View) HttpUrl(okhttp3.HttpUrl) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Animatable(android.graphics.drawable.Animatable) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) Nullable(javax.annotation.Nullable) Flowable(io.reactivex.Flowable)

Aggregations

Flowable (io.reactivex.Flowable)62 Test (org.junit.Test)27 List (java.util.List)20 TimeUnit (java.util.concurrent.TimeUnit)18 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 Observable (io.reactivex.Observable)12 Collections (java.util.Collections)11 Response (javax.ws.rs.core.Response)11 GenericType (javax.ws.rs.core.GenericType)10