io.reactivex.FlowableEmitter Java Examples

The following examples show how to use io.reactivex.FlowableEmitter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FirebaseInAppMessagingFlowableTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
private static TestSubscriber<InAppMessage> listenerToFlowable(FirebaseInAppMessaging instance) {
  Flowable<InAppMessage> listenerFlowable =
      Flowable.create(
          new FlowableOnSubscribe<InAppMessage>() {
            @Override
            public void subscribe(FlowableEmitter<InAppMessage> emitter) throws Exception {
              instance.setMessageDisplayComponent(
                  new FirebaseInAppMessagingDisplay() {
                    @Override
                    public void displayMessage(
                        InAppMessage inAppMessage,
                        FirebaseInAppMessagingDisplayCallbacks callbacks) {
                      emitter.onNext(inAppMessage);
                      Log.i("FIAM", "Putting callback for IAM " + inAppMessage.getCampaignName());
                      callbacksHashMap.put(inAppMessage.getCampaignId(), callbacks);
                    }
                  });
            }
          },
          BUFFER);
  return listenerFlowable.test();
}
 
Example #2
Source File: RxEasyHttpManager.java    From EasyHttp with Apache License 2.0 6 votes vote down vote up
@Override
public void subscribe(FlowableEmitter<T> e) throws Exception {
	try {
		Response response = call.execute();

		if (!e.isCancelled()) {
			if (response.isSuccessful()) {
				e.onNext(rxEasyConverter.convert(response.body().string()));
			} else {
				e.onError(new Throwable("response is unsuccessful"));
			}
		}
	} catch (Throwable t) {
		if (!e.isCancelled()) {
			e.onError(t);
		}
	} finally {
		e.onComplete();
	}
}
 
Example #3
Source File: ZeroFiveNewsDetailModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ZeroFiveNewsDetail> getAcgNewsDetail(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ZeroFiveNewsDetail>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ZeroFiveNewsDetail> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ZeroFiveNewsDetail zeroFiveNewsDetail = JP.from(html, ZeroFiveNewsDetail.class);
        e.onNext(zeroFiveNewsDetail);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #4
Source File: FlowableEmitterMqttActionListenerTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenTheConstructorIsCalledWithAValidEmitterThenGetOnErrorReturnsTheEmitter() {

    // Given
    @SuppressWarnings("unchecked")
    final FlowableEmitter<Object> emitter = Mockito
            .mock(FlowableEmitter.class);
    final Throwable ex = Mockito.mock(Throwable.class);
    final FlowableEmitterMqttActionListener<Object> listener = new FlowableEmitterMqttActionListener<Object>(
            emitter) {

        @Override
        public void onSuccess(final IMqttToken asyncActionToken) {
            // Not invoked
        }
    };

    // When
    final OnError onError = listener.getOnError();
    onError.onError(ex);

    // Then
    Mockito.verify(emitter).onError(ex);
}
 
Example #5
Source File: ScheduleDetailModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleDetail> getScheduleDetail(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleDetail>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleDetail> e) throws Exception {
      String scheduleLink = url;
      if (!url.contains("http")) {
        scheduleLink = HtmlConstant.YHDM_M_URL + url;
      }
      Element html = Jsoup.connect(scheduleLink).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ScheduleDetail scheduleDetail = JP.from(html, ScheduleDetail.class);
        e.onNext(scheduleDetail);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #6
Source File: AsyncAspect.java    From SAF-AOP with Apache License 2.0 6 votes vote down vote up
private void asyncMethod(final ProceedingJoinPoint joinPoint) throws Throwable {

        Flowable.create(new FlowableOnSubscribe<Object>() {
                            @Override
                            public void subscribe(FlowableEmitter<Object> e) throws Exception {
                                Looper.prepare();
                                try {
                                    joinPoint.proceed();
                                } catch (Throwable throwable) {
                                    throwable.printStackTrace();
                                }
                                Looper.loop();
                            }
                        }
                , BackpressureStrategy.BUFFER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
    }
 
Example #7
Source File: SimpleRemoteSourceMapper.java    From mvvm-template with GNU General Public License v3.0 6 votes vote down vote up
public SimpleRemoteSourceMapper(FlowableEmitter<Resource<T>> emitter) {
    emitter.onNext(Resource.loading(null));
    // since realm instance was created on Main Thread, so if we need to touch on realm database after calling
    // api (such as save response data to local database, we must make request on main thread
    // by setting shouldUpdateUi params = true
    Disposable disposable = RestHelper.makeRequest(getRemote(), true, response -> {
        Log.d(TAG, "SimpleRemoteSourceMapper: call API success!");
        saveCallResult(response);
        emitter.onNext(Resource.success(response));
    }, errorEntity -> {
        Log.d(TAG, "SimpleRemoteSourceMapper: call API error: " + errorEntity.getMessage());
        emitter.onNext(Resource.error(errorEntity.getMessage(), null));
    });

    // set emitter disposable to ensure that when it is going to be disposed, our api request should be disposed as well
    emitter.setDisposable(disposable);
}
 
Example #8
Source File: ScheduleDAO.java    From AcgClub with MIT License 6 votes vote down vote up
public Flowable<Boolean> deleteScheduleCacheByUrl(final String url) {
  return RxRealmUtils
      .flowableExec(realmConfiguration, new Consumer<Pair<FlowableEmitter, Realm>>() {
        @Override
        public void accept(final Pair<FlowableEmitter, Realm> pair) throws Exception {
          pair.second.executeTransactionAsync(new Transaction() {
            @Override
            public void execute(Realm r) {
              final boolean isSuccess = r.where(ScheduleCache.class)
                  .equalTo("scheduleUrl", url)
                  .findAll()
                  .deleteAllFromRealm();
              pair.first.onNext(isSuccess);
              pair.first.onComplete();
            }
          });
        }
      });
}
 
Example #9
Source File: ScheduleOtherModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleOtherPage> getScheduleOtherPage(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleOtherPage>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleOtherPage> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if (html == null) {
        e.onError(new Throwable("element html is null"));
      } else {
        ScheduleOtherPage scheduleOtherPage = JP.from(html, ScheduleOtherPage.class);
        e.onNext(scheduleOtherPage);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #10
Source File: RxQuery.java    From ObjectBoxRxJava with Apache License 2.0 6 votes vote down vote up
static <T> void createListItemEmitter(final Query<T> query, final FlowableEmitter<T> emitter) {
    final DataSubscription dataSubscription = query.subscribe().observer(new DataObserver<List<T>>() {
        @Override
        public void onData(List<T> data) {
            for (T datum : data) {
                if (emitter.isCancelled()) {
                    return;
                } else {
                    emitter.onNext(datum);
                }
            }
            if (!emitter.isCancelled()) {
                emitter.onComplete();
            }
        }
    });
    emitter.setCancellable(new Cancellable() {
        @Override
        public void cancel() throws Exception {
            dataSubscription.cancel();
        }
    });
}
 
Example #11
Source File: ScheduleVideoModel.java    From AcgClub with MIT License 6 votes vote down vote up
@Override
public Flowable<ScheduleVideo> getScheduleVideo(final String url) {
  return Flowable.create(new FlowableOnSubscribe<ScheduleVideo>() {
    @Override
    public void subscribe(@NonNull FlowableEmitter<ScheduleVideo> e) throws Exception {
      Element html = Jsoup.connect(url).get();
      if(html == null){
        e.onError(new Throwable("element html is null"));
      }else {
        ScheduleVideo scheduleVideo = JP.from(html, ScheduleVideo.class);
        if (!TextUtils.isEmpty(scheduleVideo.getVideoHtml())) {
          scheduleVideo.setVideoUrl("http://tup.yhdm.tv/?m=1&vid=" + scheduleVideo.getVideoUrl());
        }
        /*StringBuilder scheduleVideoHtmlBuilder = new StringBuilder();
        scheduleVideoHtmlBuilder.append(HtmlConstant.SCHEDULE_VIDEO_CSS);
        scheduleVideoHtmlBuilder.append("<div class=\"player_main\" style=\"position: relative;\"> ");
        scheduleVideoHtmlBuilder.append(scheduleVideo.getVideoHtml());
        scheduleVideoHtmlBuilder.append("</div>");
        scheduleVideo.setVideoHtml(scheduleVideoHtmlBuilder.toString());*/
        e.onNext(scheduleVideo);
        e.onComplete();
      }
    }
  }, BackpressureStrategy.BUFFER);
}
 
Example #12
Source File: SubscriberMqttMessageListenerTest.java    From rxmqtt with Apache License 2.0 6 votes vote down vote up
@Test
public void whenAMessageArrivesThenTheObserverIsNotified()
        throws Exception {
    @SuppressWarnings("unchecked")
    final FlowableEmitter<MqttMessage> observer = Mockito
            .mock(FlowableEmitter.class);
    final IMqttMessageListener listener = new SubscriberMqttMessageListener(
            observer);
    final String expectedTopic = "expected";
    final byte[] expectedPayload = new byte[] { 'a', 'b', 'c' };
    final org.eclipse.paho.client.mqttv3.MqttMessage expectedMessage = new org.eclipse.paho.client.mqttv3.MqttMessage(
            expectedPayload);
    expectedMessage.setQos(2);
    expectedMessage.setId(1);
    expectedMessage.setRetained(true);
    final ArgumentCaptor<SubscribeMessage> actualMessage = ArgumentCaptor
            .forClass(SubscribeMessage.class);
    listener.messageArrived(expectedTopic, expectedMessage);
    Mockito.verify(observer).onNext(actualMessage.capture());
    Assert.assertArrayEquals(expectedPayload,
            actualMessage.getValue().getPayload());
    Assert.assertEquals(2, actualMessage.getValue().getQos());
    Assert.assertEquals(1, actualMessage.getValue().getId());
    Assert.assertTrue(actualMessage.getValue().isRetained());
    Assert.assertEquals(expectedTopic, actualMessage.getValue().getTopic());
}
 
Example #13
Source File: ViewClickOnSubscribe.java    From RxComboDetector with MIT License 6 votes vote down vote up
@Override
public void subscribe(final FlowableEmitter<Integer> emitter) throws Exception {
    checkUiThread();

    View.OnClickListener listener = v -> {
        if (!emitter.isCancelled()) {
            emitter.onNext(1);
        }
    };
    view.setOnClickListener(listener);

    emitter.setDisposable(new MainThreadDisposable() {
        @Override
        protected void onDispose() {
            view.setOnClickListener(null);
        }
    });
}
 
Example #14
Source File: RxLocationFlowableOnSubscribe.java    From RxGps with Apache License 2.0 6 votes vote down vote up
@Override
public final void subscribe(FlowableEmitter<T> emitter) throws Exception {
    final GoogleApiClient apiClient = createApiClient(new ApiClientConnectionCallbacks(emitter));

    try {
        apiClient.connect();
    } catch (Throwable ex) {
        emitter.onError(ex);
    }

    emitter.setCancellable(() -> {
        if (apiClient.isConnected()) {
            onUnsubscribed(apiClient);
        }

        apiClient.disconnect();
    });
}
 
Example #15
Source File: Transformers.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
public static <State, In, Out> FlowableTransformer<In, Out> stateMachine(Callable<? extends State> initialState,
        Function3<? super State, ? super In, ? super FlowableEmitter<Out>, ? extends State> transition,
        BiPredicate<? super State, ? super FlowableEmitter<Out>> completion,
        BackpressureStrategy backpressureStrategy, int requestBatchSize) {
    return TransformerStateMachine.create(initialState, transition, completion, backpressureStrategy,
            requestBatchSize);
}
 
Example #16
Source File: GeodeBackend.java    From immutables with Apache License 2.0 5 votes vote down vote up
private <T> Publisher<WatchEvent<T>> watch(StandardOperations.Watch operation) {
  return Flowable.create(e -> {
    final FlowableEmitter<WatchEvent<T>> emitter = e.serialize();
    final String oql = oqlGenerator().withoutBindVariables().generate(operation.query()).oql();
    final CqAttributesFactory factory = new CqAttributesFactory();
    factory.addCqListener(new GeodeEventListener<>(oql, emitter));
    final CqQuery cqQuery = queryService.newCq(oql, factory.create());
    emitter.setDisposable(new CqDisposable(cqQuery));
    cqQuery.execute();
  }, BackpressureStrategy.ERROR);
}
 
Example #17
Source File: TransformerStateMachine.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
public static <State, In, Out> FlowableTransformer<In, Out> create(Callable<? extends State> initialState,
        Function3<? super State, ? super In, ? super FlowableEmitter<Out>, ? extends State> transition,
        BiPredicate<? super State, ? super FlowableEmitter<Out>> completion,
        BackpressureStrategy backpressureStrategy, int requestBatchSize) {
    return new TransformerStateMachine<State, In, Out>(initialState, transition, completion, backpressureStrategy,
            requestBatchSize);
}
 
Example #18
Source File: TransformerStateMachine.java    From rxjava2-extras with Apache License 2.0 5 votes vote down vote up
private TransformerStateMachine(Callable<? extends State> initialState,
        Function3<? super State, ? super In, ? super FlowableEmitter<Out>, ? extends State> transition,
        BiPredicate<? super State, ? super FlowableEmitter<Out>> completion,
        BackpressureStrategy backpressureStrategy, int requestBatchSize) {
    Preconditions.checkNotNull(initialState);
    Preconditions.checkNotNull(transition);
    Preconditions.checkNotNull(completion);
    Preconditions.checkNotNull(backpressureStrategy);
    Preconditions.checkArgument(requestBatchSize > 0, "initialRequest must be greater than zero");
    this.initialState = initialState;
    this.transition = transition;
    this.completion = completion;
    this.backpressureStrategy = backpressureStrategy;
    this.requestBatchSize = requestBatchSize;
}
 
Example #19
Source File: ChapterSeven.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo3() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            Log.d(TAG, "emit 1");
            emitter.onNext(1);
            Log.d(TAG, "emit 2");
            emitter.onNext(2);
            Log.d(TAG, "emit 3");
            emitter.onNext(3);
            Log.d(TAG, "emit complete");
            emitter.onComplete();
        }
    }, BackpressureStrategy.ERROR).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #20
Source File: QQLoginInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void fetchUserInfo(final BaseToken token) {
    Flowable.create(new FlowableOnSubscribe<QQUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<QQUser> qqUserEmitter) throws Exception {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(buildUserInfoUrl(token, URL)).build();

            try {
                Response response = client.newCall(request).execute();
                JSONObject jsonObject = new JSONObject(response.body().string());
                QQUser user = QQUser.parse(token.getOpenid(), jsonObject);
                qqUserEmitter.onNext(user);
            } catch (IOException | JSONException e) {
                ShareLogger.e(INFO.FETCH_USER_INOF_ERROR);
                qqUserEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<QQUser>() {
                @Override
                public void accept(@NonNull QQUser qqUser) throws Exception {
                    mLoginListener.loginSuccess(
                            new LoginResult(LoginPlatform.QQ, token, qqUser));
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable));
                }
            });
}
 
Example #21
Source File: ChapterNine.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo1() {
    Flowable
            .create(new FlowableOnSubscribe<Integer>() {
                @Override
                public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
                    Log.d(TAG, "current requested: " + emitter.requested());
                }
            }, BackpressureStrategy.ERROR)
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                    s.request(10);
                    s.request(100);
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #22
Source File: LocationUpdatesFlowableOnSubscribe.java    From RxGps with Apache License 2.0 5 votes vote down vote up
@Override
protected void onGoogleApiClientReady(GoogleApiClient apiClient, FlowableEmitter<Location> emitter) {
    locationListener = new RxLocationListener(emitter);

    //noinspection MissingPermission
    setupLocationPendingResult(
            LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, locationRequest, locationListener, looper),
            new StatusErrorResultCallBack(emitter)
    );
}
 
Example #23
Source File: ChapterEight.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo3() {
    Flowable.create(new FlowableOnSubscribe<Integer>() {
        @Override
        public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
            for (int i = 0; i < 10000; i++) {
                emitter.onNext(i);
            }
        }
    }, BackpressureStrategy.DROP).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                    s.request(128);
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}
 
Example #24
Source File: JsonRpc2_0Rx.java    From web3j with Apache License 2.0 5 votes vote down vote up
private <T> void run(
        org.web3j.protocol.core.filters.Filter<T> filter,
        FlowableEmitter<? super T> emitter,
        long pollingInterval) {

    filter.run(scheduledExecutorService, pollingInterval);
    emitter.setCancellable(filter::cancel);
}
 
Example #25
Source File: WxLoginInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void fetchUserInfo(final BaseToken token) {
    Flowable.create(new FlowableOnSubscribe<WxUser>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<WxUser> wxUserEmitter) throws Exception {
            Request request = new Request.Builder().url(buildUserInfoUrl(token)).build();
            try {
                Response response = mClient.newCall(request).execute();
                JSONObject jsonObject = new JSONObject(response.body().string());
                WxUser user = WxUser.parse(jsonObject);
                wxUserEmitter.onNext(user);
            } catch (IOException | JSONException e) {
                wxUserEmitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<WxUser>() {
                @Override
                public void accept(WxUser wxUser) {
                    mLoginListener.loginSuccess(
                            new LoginResult(LoginPlatform.WX, token, wxUser));
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    mLoginListener.loginFailure(new Exception(throwable));
                }
            });
}
 
Example #26
Source File: RxBus.java    From KotlinMVPRxJava2Dagger2GreenDaoRetrofitDemo with Apache License 2.0 5 votes vote down vote up
private RxBus() {
    flowable = Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<T> e) throws Exception {
            emmiter = e;
        }
    }, BackpressureStrategy.ERROR);
}
 
Example #27
Source File: RxQuery.java    From ObjectBoxRxJava with Apache License 2.0 5 votes vote down vote up
/**
 * The returned Flowable emits Query results one by one. Once all results have been processed, onComplete is called.
 * Uses given BackpressureStrategy.
 */
public static <T> Flowable<T> flowableOneByOne(final Query<T> query, BackpressureStrategy strategy) {
    return Flowable.create(new FlowableOnSubscribe<T>() {
        @Override
        public void subscribe(final FlowableEmitter<T> emitter) throws Exception {
            createListItemEmitter(query, emitter);
        }

    }, strategy);
}
 
Example #28
Source File: QQShareInstance.java    From smart-farmer-android with Apache License 2.0 5 votes vote down vote up
@Override
public void shareImage(final int platform, final ShareImageObject shareImageObject,
        final Activity activity, final ShareListener listener) {
    Flowable.create(new FlowableOnSubscribe<String>() {
        @Override
        public void subscribe(@NonNull FlowableEmitter<String> emitter) throws Exception {
            try {
                emitter.onNext(ImageDecoder.decode(activity, shareImageObject));
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }
    }, BackpressureStrategy.DROP)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnRequest(new LongConsumer() {
                @Override
                public void accept(long aLong) {
                    listener.shareRequest();
                }
            })
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String localPath) {
                    if (platform == SharePlatform.QZONE) {
                        shareToQzoneForImage(localPath, activity, listener);
                    } else {
                        shareToQQForImage(localPath, activity, listener);
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {
                    activity.finish();
                    listener.shareFailure(new Exception(throwable));
                }
            });
}
 
Example #29
Source File: ViewClickOnSubscribe.java    From dapp-wallet-demo with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribe(FlowableEmitter<View> emitter) throws Exception {
    verifyMainThread();
    View.OnClickListener listener = v -> {
        if (!emitter.isCancelled()){
            emitter.onNext(v);
        }
    };
    view.setOnClickListener(listener);
    emitter.setCancellable(() -> view.setOnClickListener(null));
}
 
Example #30
Source File: ChapterNine.java    From RxJava2Demo with Apache License 2.0 5 votes vote down vote up
public static void demo3() {
    Flowable
            .create(new FlowableOnSubscribe<Integer>() {
                @Override
                public void subscribe(FlowableEmitter<Integer> emitter) throws Exception {
                    Log.d(TAG, "current requested: " + emitter.requested());
                }
            }, BackpressureStrategy.ERROR)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Integer>() {

                @Override
                public void onSubscribe(Subscription s) {
                    Log.d(TAG, "onSubscribe");
                    mSubscription = s;
                    s.request(1000);
                }

                @Override
                public void onNext(Integer integer) {
                    Log.d(TAG, "onNext: " + integer);
                }

                @Override
                public void onError(Throwable t) {
                    Log.w(TAG, "onError: ", t);
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "onComplete");
                }
            });
}