io.reactivex.rxjava3.core.Observable Java Examples

The following examples show how to use io.reactivex.rxjava3.core.Observable. 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: RxMobius.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Add an {@link ObservableTransformer} for handling effects of a given type. The handler will
 * receive all effect objects that extend the given class.
 *
 * <p>Adding handlers for two effect classes where one is a super-class of the other is
 * considered a collision and is not allowed. Registering the same class twice is also
 * considered a collision.
 *
 * @param effectClass the class to handle
 * @param effectHandler the effect handler for the given effect class
 * @param <G> the effect class as a type parameter
 * @return this builder
 * @throws IllegalArgumentException if there is a handler collision
 */
public <G extends F> RxMobius.SubtypeEffectHandlerBuilder<F, E> addTransformer(
    final Class<G> effectClass, final ObservableTransformer<G, E> effectHandler) {
  checkNotNull(effectClass);
  checkNotNull(effectHandler);

  for (Class<?> cls : effectPerformerMap.keySet()) {
    if (cls.isAssignableFrom(effectClass) || effectClass.isAssignableFrom(cls)) {
      throw new IllegalArgumentException(
          "Effect classes may not be assignable to each other, collision found: "
              + effectClass.getSimpleName()
              + " <-> "
              + cls.getSimpleName());
    }
  }

  effectPerformerMap.put(
      effectClass,
      (Observable<F> effects) ->
          effects
              .ofType(effectClass)
              .compose(effectHandler)
              .doOnError(onErrorFunction.apply(effectHandler)));

  return this;
}
 
Example #2
Source File: TestWithSpring.java    From RxCache with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        ApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);

        RxCache rxCache = (RxCache) ctx.getBean("rxCache");

        User u = new User();
        u.name = "tony";
        u.password = "123456";
        rxCache.save("test",u);

        Observable<Record<User>> observable = rxCache.load2Observable("test", User.class);

        observable.subscribe(new Consumer<Record<User>>() {

            @Override
            public void accept(Record<User> record) throws Exception {

                User user = record.getData();
                System.out.println(user.name);
                System.out.println(user.password);
            }
        });
    }
 
Example #3
Source File: RxMobiusLoopTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowIfStartingALoopWithInitAndStartEffects() throws Exception {
  MobiusLoop.Builder<String, Integer, Boolean> withInit =
      builder.init(
          new Init<String, Boolean>() {
            @Nonnull
            @Override
            public First<String, Boolean> init(String model) {
              return First.first(model + "-init");
            }
          });

  ObservableTransformer<Integer, String> transformer =
      RxMobius.loopFrom(withInit, "hi", effects(true));

  Observable.just(10)
      .compose(transformer)
      .test()
      .assertError(t -> t.getMessage().contains("cannot pass in start effects"));
}
 
Example #4
Source File: TestDiskImplWithMoshi.java    From RxCache with Apache License 2.0 6 votes vote down vote up
private static void testObject(RxCache rxCache) {

        User u = new User();
        u.name = "tony";
        u.password = "123456";
        rxCache.save("test", u);

        Observable<Record<User>> observable = rxCache.load2Observable("test", User.class);

        observable.subscribe(new Consumer<Record<User>>() {

            @Override
            public void accept(Record<User> record) throws Exception {

                User user = record.getData();
                System.out.println(user.name);
                System.out.println(user.password);
            }
        });
    }
 
Example #5
Source File: TransformersTest.java    From mobius with Apache License 2.0 6 votes vote down vote up
@Test
public void processingLongEffectsDoesNotBlockProcessingShorterEffects() {
  final List<String> effects = Arrays.asList("Hello", "Rx");

  PublishSubject<String> upstream = PublishSubject.create();
  Function<String, Integer> sleepyFunction =
      s -> {
        try {
          Thread.sleep(duration(s));
        } catch (InterruptedException ie) {
        }
        return s.length();
      };

  final List<Integer> results = new ArrayList<>();
  upstream
      .compose(Transformers.fromFunction(sleepyFunction, Schedulers.io()))
      .subscribe(results::add);

  Observable.fromIterable(effects).subscribe(upstream);

  await().atMost(durationForEffects(effects)).until(() -> results.equals(expected(effects)));
}
 
Example #6
Source File: MainActivity.java    From RxLifecycle with Apache License 2.0 6 votes vote down vote up
@Override
protected void onStart() {
    super.onStart();

    Log.d(TAG, "onStart()");

    // Using automatic unsubscription, this should determine that the correct time to
    // unsubscribe is onStop (the opposite of onStart).
    Observable.interval(1, TimeUnit.SECONDS)
        .doOnDispose(new Action() {
            @Override
            public void run() throws Exception {
                Log.i(TAG, "Unsubscribing subscription from onStart()");
            }
        })
        .compose(this.<Long>bindToLifecycle())
        .subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long num) throws Exception {
                Log.i(TAG, "Started in onStart(), running until in onStop(): " + num);
            }
        });
}
 
Example #7
Source File: Transformers.java    From mobius with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link ObservableTransformer} that will flatten the provided {@link Consumer} into
 * the stream as a {@link Completable} every time it receives an effect from the upstream effects
 * observable. This will result in calling the consumer on the specified scheduler, and passing it
 * the requested effect object.
 *
 * @param doEffect the {@link Consumer} to be run every time the effect is requested
 * @param scheduler the {@link Scheduler} to be used when invoking the consumer
 * @param <F> the type of Effect this transformer handles
 * @param <E> these transformers are for effects that do not result in any events; however, they
 *     still need to share the same Event type
 * @return an {@link ObservableTransformer} that can be used with a {@link
 *     RxMobius.SubtypeEffectHandlerBuilder}.
 */
static <F, E> ObservableTransformer<F, E> fromConsumer(
    final Consumer<F> doEffect, @Nullable final Scheduler scheduler) {
  return new ObservableTransformer<F, E>() {
    @Override
    public ObservableSource<E> apply(Observable<F> effectStream) {
      return effectStream
          .flatMapCompletable(
              new Function<F, CompletableSource>() {
                @Override
                public CompletableSource apply(final F effect) {
                  Completable completable =
                      Completable.fromAction(
                          new Action() {
                            @Override
                            public void run() throws Throwable {
                              doEffect.accept(effect);
                            }
                          });
                  return scheduler == null ? completable : completable.subscribeOn(scheduler);
                }
              })
          .toObservable();
    }
  };
}
 
Example #8
Source File: RxJava3Test.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void consumerTest3WithError(final MockTracer tracer) {
  final Observable<Integer> observable = createSequentialObservable(tracer, true);
  final List<Integer> result = new ArrayList<>();
  final Consumer<Integer> onNext = consumer(result);
  final List<String> completeList = new ArrayList<>();
  final List<String> errorList = new ArrayList<>();
  observable.subscribe(onNext, onError(errorList), onComplete(completeList, tracer));

  assertEquals(0, result.size());
  assertEquals(0, completeList.size());
  assertEquals(1, errorList.size());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());

  assertNull(tracer.scopeManager().active());
}
 
Example #9
Source File: JAXRSRxJava3ObservableTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHelloWorldJson() throws Exception {
    String address = "http://localhost:" + PORT + "/rx3/observable/textJson";
    List<Object> providers = new LinkedList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new ObservableRxInvokerProvider());
    WebClient wc = WebClient.create(address, providers);
    Observable<HelloWorldBean> obs = wc.accept("application/json")
        .rx(ObservableRxInvoker.class)
        .get(HelloWorldBean.class);

    Holder<HelloWorldBean> holder = new Holder<>();
    Disposable d = obs.subscribe(v -> {
        holder.value = v;
    });
    if (d == null) {
        throw new IllegalStateException("Subscribe did not return a Disposable");
    }
    Thread.sleep(2000);
    assertEquals("Hello", holder.value.getGreeting());
    assertEquals("World", holder.value.getAudience());
}
 
Example #10
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nonnull
@CheckReturnValue
public Observable<JsonArray> getReactionsRaw(@Nonnull final String channelId, @Nonnull final String messageId,
                                             @Nonnull final String emoji, @Nullable final String before,
                                             @Nullable final String after, @Nonnegative final int limit) {
    
    final QueryStringBuilder builder = new QueryStringBuilder();
    if(limit > 0) {
        builder.append("limit", Integer.toString(limit));
    }
    if(before != null) {
        builder.append("before", before);
    }
    
    if(after != null) {
        builder.append("after", after);
    }
    
    final String query = builder.build();
    return catnip().requester()
            .queue(new OutboundRequest(Routes.GET_REACTIONS.withMajorParam(channelId).withQueryString(query),
                    Map.of("message", messageId, "emojis", encodeUTF8(emoji))))
            .map(ResponsePayload::array);
}
 
Example #11
Source File: CacheAndRemoteStrategy.java    From RxCache with Apache License 2.0 6 votes vote down vote up
@Override
public <T> Observable<Record<T>> execute(RxCache rxCache, String key, Observable<T> source, Type type) {

    Observable<Record<T>> cache = rxCache.<T>load2Observable(key, type);

    Observable<Record<T>> remote = source
            .map(new Function<T, Record<T>>() {
                @Override
                public Record<T> apply(@NonNull T t) throws Exception {

                    rxCache.save(key, t);

                    return new Record<>(Source.CLOUD, key, t);
                }
            });

    return Observable.concatDelayError(Arrays.asList(cache, remote))
            .filter(new Predicate<Record<T>>() {
                @Override
                public boolean test(@NonNull Record<T> record) throws Exception {
                    return record.getData() != null;
                }
            });
}
 
Example #12
Source File: TestDiskImplWithMoshi.java    From RxCache with Apache License 2.0 5 votes vote down vote up
private static void testSet(RxCache rxCache) {

        Set<User> set = new HashSet<>();

        User u1 = new User();
        u1.name = "tonySet1";
        u1.password = "set1123456";
        set.add(u1);

        User u2 = new User();
        u2.name = "tonySet12";
        u2.password = "set12345";
        set.add(u2);
        rxCache.save("set", set);

        Type type = TypeBuilder
                .newInstance(Set.class)
                .addTypeParam(User.class)
                .build();

        Observable<Record<Set<User>>> observable = rxCache.load2Observable("set", type);

        observable.subscribe(new Consumer<Record<Set<User>>>() {

            @Override
            public void accept(Record<Set<User>> record) throws Exception {

                Set<User> recordDataList = record.getData();

                if (Preconditions.isNotBlank(recordDataList)) {
                    for (User user : recordDataList) {
                        System.out.println(user.name);
                        System.out.println(user.password);
                    }
                }
            }
        });
    }
 
Example #13
Source File: PixelTraversalController.java    From Image-Cipher with Apache License 2.0 5 votes vote down vote up
void setClickObservable(Observable<Point> observable) {
  logger.info("Setting observable");
  disposable = observable.subscribeOn(Schedulers.computation())
      .subscribe(point -> {
        startingPoint = point;
        runPixelTraversal();
      });
}
 
Example #14
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public Observable<CreatedInvite> getGuildInvites(@Nonnull final String guildId) {
    return getGuildInvitesRaw(guildId)
            .map(e -> mapObjectContents(entityBuilder()::createCreatedInvite).apply(e))
            .flatMapIterable(e -> e);
}
 
Example #15
Source File: ClauDB.java    From claudb with MIT License 5 votes vote down vote up
@Override
public void importRDB(InputStream input) {
  executeOn(Observable.create(observable -> {
    getState().importRDB(input);
    observable.onComplete();
  })).blockingSubscribe();
}
 
Example #16
Source File: BasePaginator.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Fetches up to {@link #limit(int) limit} entities, returning a list
 * containing all of them.
 * <br><b>This method will keep all entities in memory</b>, so for unbounded
 * pagination it should be avoided.
 *
 * @return A list containing all the fetched entities.
 */
@Nonnull
@CheckReturnValue
public Observable<T> fetch() {
    final List<T> list = new ArrayList<>();
    return forEach(list::add)
            .map(__ -> Collections.unmodifiableList(list))
            .flatMapIterable(e -> e);
}
 
Example #17
Source File: ObserverRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDelaySubscription() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(1).toNanos());

    Observable.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .awaitDone(2, TimeUnit.SECONDS);
}
 
Example #18
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public Observable<JsonObject> getGuildPruneCountRaw(@Nonnull final String guildId, @Nonnegative final int days) {
    final String query = new QueryStringBuilder().append("days", Integer.toString(days)).build();
    return catnip().requester().queue(new OutboundRequest(Routes.GET_GUILD_PRUNE_COUNT
            .withMajorParam(guildId).withQueryString(query), Map.of()))
            .map(ResponsePayload::object);
}
 
Example #19
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public AuditLogPaginator getGuildAuditLog(@Nonnull final String guildId) {
    return new AuditLogPaginator(entityBuilder()) {
        @Nonnull
        @CheckReturnValue
        @Override
        protected Observable<JsonObject> fetchNext(@Nonnull final RequestState<AuditLogEntry> state, @Nullable final String lastId,
                                                   @Nonnegative final int requestSize) {
            return getGuildAuditLogRaw(guildId, state.extra("user"), lastId, state.extra("type"), requestSize);
        }
    };
}
 
Example #20
Source File: BehaviorRelayTest.java    From RxRelay with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void testUnsubscriptionCase() {
    BehaviorRelay<String> src = BehaviorRelay.createDefault("null"); // FIXME was plain null which is not allowed

    for (int i = 0; i < 10; i++) {
        final Observer<Object> o = TestHelper.mockObserver();
        InOrder inOrder = inOrder(o);
        String v = "" + i;
        src.accept(v);
        System.out.printf("Turn: %d%n", i);
        src.firstElement()
            .toObservable()
            .flatMap(new Function<String, Observable<String>>() {

                @Override
                public Observable<String> apply(String t1) {
                    return Observable.just(t1 + ", " + t1);
                }
            })
            .subscribe(new DefaultObserver<String>() {
                @Override
                public void onNext(String t) {
                    o.onNext(t);
                }

                @Override
                public void onError(Throwable e) {
                    o.onError(e);
                }

                @Override
                public void onComplete() {
                    o.onComplete();
                }
            });
        inOrder.verify(o).onNext(v + ", " + v);
        inOrder.verify(o).onComplete();
        verify(o, never()).onError(any(Throwable.class));
    }
}
 
Example #21
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public Observable<JsonObject> createGuildRoleRaw(@Nonnull final String guildId, @Nonnull final RoleData roleData,
                                                 @Nullable final String reason) {
    return catnip().requester()
            .queue(new OutboundRequest(Routes.CREATE_GUILD_ROLE.withMajorParam(guildId),
                    Map.of(), roleData.toJson(), reason))
            .map(ResponsePayload::object);
}
 
Example #22
Source File: RestGuild.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
@CheckReturnValue
public Observable<JsonArray> getGuildChannelsRaw(@Nonnull final String guildId) {
    return catnip().requester()
            .queue(new OutboundRequest(Routes.GET_GUILD_CHANNELS.withMajorParam(guildId),
                    Map.of()))
            .map(ResponsePayload::array);
}
 
Example #23
Source File: RestUser.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Nonnull
public Observable<JsonObject> modifyCurrentUserRaw(@Nullable final String username, @Nullable final URI avatarData) {
    final JsonObject body = new JsonObject();
    if(avatarData != null) {
        Utils.validateImageUri(avatarData);
        body.put("avatar", avatarData.toString());
    }
    body.put("username", username);
    
    return catnip().requester().queue(new OutboundRequest(Routes.MODIFY_CURRENT_USER,
            Map.of(), body))
            .map(ResponsePayload::object);
}
 
Example #24
Source File: RxBoxStore.java    From objectbox-java with Apache License 2.0 5 votes vote down vote up
/**
 * Using the returned Observable, you can be notified about data changes.
 * Once a transaction is committed, you will get info on classes with changed Objects.
 */
@SuppressWarnings("rawtypes") // BoxStore observer may return any (entity) type.
public static Observable<Class> observable(BoxStore boxStore) {
    return Observable.create(emitter -> {
        final DataSubscription dataSubscription = boxStore.subscribe().observer(data -> {
            if (!emitter.isDisposed()) {
                emitter.onNext(data);
            }
        });
        emitter.setCancellable(dataSubscription::cancel);
    });
}
 
Example #25
Source File: TextChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Fetch all webhooks on this channel.
 *
 * @return A not-{@code null}, possibly-empty list of webhooks for this
 * channel.
 */
@Nonnull
@CheckReturnValue
default Observable<Webhook> fetchWebhooks() {
    PermissionUtil.checkPermissions(catnip(), guildId(), id(), Permission.MANAGE_WEBHOOKS);
    return catnip().rest().webhook().getChannelWebhooks(id());
}
 
Example #26
Source File: PolledObservablePair.java    From consensusj with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param pair The currency pair to observe
 * @param rateSupplier A polling Supplier function (for a single pair)
 * @param interval An interval (or equivalent) to provide clock ticks to trigger polling
 */
public PolledObservablePair(CurrencyUnitPair pair, Supplier<ExchangeRateUpdate> rateSupplier, Observable<Long> interval) {
    this.pair = pair;
    observablePairUpdates = interval
            .map(l -> rateSupplier.get())   // Use the Supplier function to do the polling
            .replay(1)            // Create a ConnectableObservable that can start and stop polling
            .refCount();                    // Create a refCount-tracking observable to share the ConnectableObservable
}
 
Example #27
Source File: ObserverRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitSingleEventWithSinglePermit() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Observable.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertResult(1);
}
 
Example #28
Source File: RestChannel.java    From catnip with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Observable<Message> getChannelMessages(@Nonnull final String channelId, @Nullable final String before,
                                              @Nullable final String after, @Nullable final String around,
                                              @Nonnegative final int limit) {
    return getChannelMessagesRaw(channelId, before, after, around, limit)
            .map(e -> mapObjectContents(entityBuilder()::createMessage).apply(e))
            .flatMapIterable(e -> e);
}
 
Example #29
Source File: ReactiveIOInvoker.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected AsyncResponseImpl handleObservable(Message inMessage, Observable<?> obs) {
    final AsyncResponseImpl asyncResponse = new AsyncResponseImpl(inMessage);
    Disposable d = obs.subscribe(v -> asyncResponse.resume(v), t -> handleThrowable(asyncResponse, t));
    if (d == null) {
        throw new IllegalStateException("Subscribe did not return a Disposable");
    }
    return asyncResponse;
}
 
Example #30
Source File: ReplayingShareObservableTest.java    From RxReplayingShare with Apache License 2.0 5 votes vote down vote up
@Test public void initialValueToNewSubscriber() {
  PublishSubject<String> subject = PublishSubject.create();
  Observable<String> observable = subject.compose(ReplayingShare.<String>instance());

  TestObserver<String> observer1 = new TestObserver<>();
  observable.subscribe(observer1);
  observer1.assertNoValues();

  subject.onNext("Foo");
  observer1.assertValues("Foo");

  TestObserver<String> observer2 = new TestObserver<>();
  observable.subscribe(observer2);
  observer2.assertValues("Foo");
}