Java Code Examples for io.reactivex.Observable#fromIterable()

The following examples show how to use io.reactivex.Observable#fromIterable() . 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: PseudoCacheMergeFragment.java    From RxJava-Android-Samples with Apache License 2.0 6 votes vote down vote up
private Observable<Pair<Contributor, Long>> _getCachedData() {

    List<Pair<Contributor, Long>> list = new ArrayList<>();

    Pair<Contributor, Long> dataWithAgePair;

    for (String username : _contributionMap.keySet()) {
      Contributor c = new Contributor();
      c.login = username;
      c.contributions = _contributionMap.get(username);

      dataWithAgePair = new Pair<>(c, System.currentTimeMillis());
      list.add(dataWithAgePair);
    }

    return Observable.fromIterable(list);
  }
 
Example 2
Source File: ParallelStreams.java    From rxjava2 with MIT License 6 votes vote down vote up
public static void main(String[] args) {

        List<Beer> beers = loadCellar();  // populate the beer collection

        Observable<Beer> observableBeers = Observable.fromIterable(beers);

        observableBeers
                .flatMap(beer -> Observable.just(beer)
                           .subscribeOn(Schedulers.computation())  // replace computation() with newThread()
                           .map(beeer -> matureBeer(beeer))
                 )
                .subscribe(beer -> System.out.println("Subscriber got " +
                               beer.name + " on  " +
                               Thread.currentThread().getName())
                );


        // Just to keep the program running
        try {
            Thread.sleep(5000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
Example 3
Source File: ObservableErrorComplete.java    From rxjava2 with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        List<Beer> beers = loadCellar();  // populate the beer collection

        System.out.println("== Observable creation from an Iterable");

        Observable<Beer> observableBeer = Observable.fromIterable(beers);

        observableBeer.subscribe(
                beer -> System.out.println(beer),
                error -> System.err.println(error),
                () -> System.out.println("Streaming is over")
        );
    }
 
Example 4
Source File: AsyncAndSyncToObservableIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenAsyncMethod_whenConvertedWithDeferFuture_thenRetrunObservble() { 
    List<Integer> list = Arrays.asList(new Integer[] { counter.incrementAndGet(), counter.incrementAndGet(), counter.incrementAndGet() });
    ExecutorService exec = Executors.newSingleThreadExecutor();
    Callable<Observable<Integer>> callable = () -> Observable.fromIterable(list);
    Observable<Integer> source = AsyncObservable.deferFuture(() -> exec.submit(callable));
    for (int i = 1; i < 4; i++) {
        source.test()
            .awaitDone(5, TimeUnit.SECONDS)
            .assertResult(1, 2, 3);
    }

    exec.shutdown();
}
 
Example 5
Source File: StreamVsObservable.java    From rxjava2 with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        List<Beer> beers = loadCellar();  // populate the beer collection

        // === Java 8 Stream
        System.out.println("\n== Iterating over Java 8 Stream");

        beers.stream()
                .skip(1)
                .limit(3)
                .filter(b -> "USA".equals(b.country))
                .map(b -> b.name + ": $" + b.price)
                .forEach(beer -> System.out.println(beer));

        // === RxJava Observable

        Observable<Beer> observableBeer = null;

        System.out.println("\n== Subscribing to Observable ");

        observableBeer = Observable.fromIterable(beers);

        observableBeer
                .skip(1)
                .take(3)
                .filter(b -> "USA".equals(b.country))
                .map(b -> b.name + ": $" + b.price)
                .subscribe(
                        beer -> System.out.println(beer),
                        err ->  System.out.println(err),
                        () ->   System.out.println("Streaming is complete"),
                        disposable -> System.out.println( " !!! Someone just subscribed to the beer stream!!! ")
        );
    }
 
Example 6
Source File: HelloObservable.java    From rxjava2 with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        List<Beer> beers = loadCellar();  // populate the beer collection

        Observable<Beer> observableBeer =
                Observable.fromIterable(beers);   // Create Observable from a List

        observableBeer.subscribe(
                beer -> System.out.println(beer)    // onNext handler
        );
    }
 
Example 7
Source File: RxJavaIterableDemo.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
public static void main(String[] args) {

		List<EmployeeRating> employeeList = new ArrayList<EmployeeRating>();

		EmployeeRating employeeRating1 = new EmployeeRating();
		employeeRating1.setName("Lilly");
		employeeRating1.setRating(6);
		employeeList.add(employeeRating1);

		employeeRating1 = new EmployeeRating();
		employeeRating1.setName("Peter");
		employeeRating1.setRating(5);
		employeeList.add(employeeRating1);

		employeeRating1 = new EmployeeRating();
		employeeRating1.setName("Bhakti");
		employeeRating1.setRating(9);
		employeeList.add(employeeRating1);

		employeeRating1 = new EmployeeRating();
		employeeRating1.setName("Harmi");
		employeeRating1.setRating(9);
		employeeList.add(employeeRating1);


		Observable<EmployeeRating> employeeRatingSource = Observable.fromIterable(employeeList);

		employeeRatingSource.filter(employeeRating -> employeeRating.getRating() >=7)
			.subscribe(empRating -> System.out.println("Star Employee: " + empRating.getName() 
				+ " Rating : "+empRating.getRating()));

	}
 
Example 8
Source File: FlowableIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test public void whenLatestStrategyUsed_thenTheLastElementReceived() {
    List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList());
    Observable observable = Observable.fromIterable(testList);
    TestSubscriber<Integer> testSubscriber = observable.toFlowable(BackpressureStrategy.LATEST).observeOn(Schedulers.computation()).test();

    testSubscriber.awaitTerminalEvent();
    List<Integer> receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList());

    assertThat(receivedInts.size() < testList.size());
    assertThat(receivedInts.contains(100000));
}
 
Example 9
Source File: FlowableIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test public void thenAllValuesAreBufferedAndReceived() {
    List testList = IntStream.range(0, 100000).boxed().collect(Collectors.toList());
    Observable observable = Observable.fromIterable(testList);
    TestSubscriber<Integer> testSubscriber = observable.toFlowable(BackpressureStrategy.BUFFER).observeOn(Schedulers.computation()).test();

    testSubscriber.awaitTerminalEvent();

    List<Integer> receivedInts = testSubscriber.getEvents().get(0).stream().mapToInt(object -> (int) object).boxed().collect(Collectors.toList());

    assertEquals(testList, receivedInts);
}
 
Example 10
Source File: DepartmentServiceImpl.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Observable<Department> getDeptsRx() {
	Observable<Department> depts= Observable.fromIterable(departmentDaoImpl.getDepartments());
	return depts;
}
 
Example 11
Source File: RxJava2PostRepository.java    From spring-reactive-sample with GNU General Public License v3.0 4 votes vote down vote up
Observable<Post> findAll() {
    return Observable.fromIterable(DATA);
}
 
Example 12
Source File: DepartmentServiceImpl.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Observable<Department> getDeptsRx() {
	Observable<Department> depts= Observable.fromIterable(departmentDaoImpl.getDepartments());
	return depts;
}
 
Example 13
Source File: DepartmentServiceImpl.java    From Spring-5.0-Cookbook with MIT License 4 votes vote down vote up
@Override
public Observable<Department> getDeptsRx() {
	Observable<Department> depts= Observable.fromIterable(departmentDaoImpl.getDepartments());
	return depts;
}
 
Example 14
Source File: ListenerBase.java    From symbol-sdk-java with Apache License 2.0 4 votes vote down vote up
public Observable<Boolean> transactionFromAddress(final Transaction transaction, final Address address,
    final Observable<List<NamespaceId>> namespaceIdsObservable) {
    if (transaction.getSigner().filter(s -> s.getAddress().equals(address)).isPresent()) {
        return Observable.just(true);
    }
    if (transaction instanceof AggregateTransaction) {
        final AggregateTransaction aggregateTransaction = (AggregateTransaction) transaction;
        if (aggregateTransaction.getCosignatures().stream()
            .anyMatch(c -> c.getSigner().getAddress().equals(address))) {
            return Observable.just(true);
        }
        //Recursion...
        Observable<Transaction> innerTransactionObservable = Observable
            .fromIterable(aggregateTransaction.getInnerTransactions());

        return innerTransactionObservable
            .flatMap(t -> this.transactionFromAddress(t, address, namespaceIdsObservable).filter(a -> a))
            .first(false).toObservable();
    }
    if (transaction instanceof PublicKeyLinkTransaction) {
        return Observable.just(Address
            .createFromPublicKey(((PublicKeyLinkTransaction) transaction).getLinkedPublicKey().toHex(),
                transaction.getNetworkType()).equals(address));
    }

    if (transaction instanceof MetadataTransaction) {
        MetadataTransaction metadataTransaction = (MetadataTransaction) transaction;
        return Observable.just(metadataTransaction.getTargetAddress().equals(address));
    }

    if (transaction instanceof TargetAddressTransaction) {
        TargetAddressTransaction targetAddressTransaction = (TargetAddressTransaction) transaction;
        if (targetAddressTransaction.getTargetAddress() instanceof Address) {
            return Observable.just(targetAddressTransaction.getTargetAddress().equals(address));
        }
        return namespaceIdsObservable
            .map(namespaceIds -> namespaceIds.contains(targetAddressTransaction.getTargetAddress()));
    }

    if (transaction instanceof MultisigAccountModificationTransaction) {
        MultisigAccountModificationTransaction multisigAccountModificationTransaction = (MultisigAccountModificationTransaction) transaction;
        if (multisigAccountModificationTransaction.getAddressAdditions().stream()
            .anyMatch(a -> a.equals(address))) {
            return Observable.just(true);
        }

        return Observable.just(
            multisigAccountModificationTransaction.getAddressDeletions().stream().anyMatch(a -> a.equals(address)));

    }

    if (transaction instanceof AccountAddressRestrictionTransaction) {
        AccountAddressRestrictionTransaction accountAddressRestrictionTransaction = (AccountAddressRestrictionTransaction) transaction;
        if (accountAddressRestrictionTransaction.getRestrictionAdditions().contains(address)) {
            return Observable.just(true);
        }
        if (accountAddressRestrictionTransaction.getRestrictionDeletions().contains(address)) {
            return Observable.just(true);
        }
        return namespaceIdsObservable.flatMap(namespaceIds -> {
            if (namespaceIds.stream().anyMatch(
                namespaceId -> accountAddressRestrictionTransaction.getRestrictionAdditions()
                    .contains(namespaceId))) {
                return Observable.just(true);
            }
            if (namespaceIds.stream().anyMatch(
                namespaceId -> accountAddressRestrictionTransaction.getRestrictionDeletions()
                    .contains(namespaceId))) {
                return Observable.just(true);
            }
            return Observable.just(false);
        });
    }

    if (transaction instanceof RecipientTransaction) {
        RecipientTransaction recipientTransaction = (RecipientTransaction) transaction;
        if (recipientTransaction.getRecipient() instanceof NamespaceId) {
            return namespaceIdsObservable
                .map(namespaceIds -> namespaceIds.contains(recipientTransaction.getRecipient()));
        }
        return Observable.just(recipientTransaction.getRecipient().equals(address));

    }

    return Observable.just(false);
}
 
Example 15
Source File: DataManager.java    From Android-ReactiveProgramming with Apache License 2.0 4 votes vote down vote up
public Observable<Integer> numbers() {
    return Observable.fromIterable(numberGenerator.numbers());
}
 
Example 16
Source File: DataManager.java    From Android-ReactiveProgramming with Apache License 2.0 4 votes vote down vote up
public Observable<Long> numbers(int upUntil) {
    return Observable.fromIterable(numberGenerator.numbers(upUntil));
}
 
Example 17
Source File: DataManager.java    From Android-ReactiveProgramming with Apache License 2.0 4 votes vote down vote up
public Observable<String> elements() {
    return Observable.fromIterable(stringGenerator.randomStringList());
}
 
Example 18
Source File: RxApplication.java    From reactive-code-workshop with Apache License 2.0 4 votes vote down vote up
private Observable<String> lines() {
    return Observable.fromIterable(() -> Jabberwocky.lines().iterator());
}
 
Example 19
Source File: RxHelloWorld.java    From tutorials with MIT License 4 votes vote down vote up
/**
 * @return an {@link Observable} that emits events "hello" and "world" before completing.
 */
public static Observable<String> hello() {
    // Guava ImmutableList class is an implementation detail.
    List<String> values = ImmutableList.of("hello", "world");
    return Observable.fromIterable(values);
}
 
Example 20
Source File: ObservableRxList.java    From adamant-android with GNU General Public License v3.0 4 votes vote down vote up
public Observable<T> getCurrentList() {
    return Observable.fromIterable(list);
}