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

The following are Jave code examples for showing how to use fromIterable() of the io.reactivex.Observable class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: rxjavatraining   File: ObservableTestingTest.java   Source Code and License Vote up 7 votes
public Observable<Tuple2<String, Double>> processStock(List<String> stocks, Function<String, String> f) {
    Observable<String> stockNames = Observable.fromIterable(stocks);
    Observable<String> urls = stockNames.map(s -> "https://finance.google.com/finance/historical?output=csv&q=" + s);
    Observable<Optional<String>> optionalObservable = urls
            .subscribeOn(Schedulers.from(executorService))
            .flatMap(s -> {
                try {
                    return Observable.just(Optional.of(f.apply(s)));
                } catch (Throwable t) {
                    return Observable.just(Optional.<String>empty());
                }
            })

            .observeOn(Schedulers.computation())
            .map(opt -> opt.map(doc -> doc.split("\n")[1].split(",")[4]))
            .doOnNext(x -> System.out.println(">>>>" + x));
    return Observable.zip(stockNames, optionalObservable, (name, price) ->
            new Tuple2<>(name, Double.parseDouble(price.orElse("0.0"))));
}
 
Example 2
Project: reactive-demo   File: reactive.java   Source Code and License Vote up 6 votes
@Test
    public void testReactive() {
        Observable.just("Hello", "World")
                .subscribe(System.out::println);
        List<String> words = Arrays.asList(
                "the",
                "quick",
                "brown",
                "fox",
                "jumps",
                "over",
                "the",
                "lazy",
                "dog"
        );

        Observable<String> wordsObs = Observable.fromIterable(words);
        wordsObs.subscribe(System.out::println);

        Observable<Integer> range = Observable.range(1, Integer.MAX_VALUE);
//        range.subscribe(System.out::println);

        wordsObs.zipWith(range, (word, row) -> String.format("%2d. %s", row, word))
                .subscribe(System.out::println);

        wordsObs.flatMap(word -> Observable.fromArray(word.split("")))
                .sorted()
                .distinct()
                .zipWith(range, (word, row) -> String.format("%2d. %s", row, word))
                .subscribe(System.out::println);
    }
 
Example 3
Project: code-examples-android-expert   File: lessonA_CreatingObservableStreams.java   Source Code and License Vote up 6 votes
/**
 * Observable.fromIterable() is another way to create an Observable. It's
 * different than .just() - it is specifically designed to work with
 * Collections. When just is given a collection, it converts it into an
 * Observable that emits each item from the list. Let's understand how the
 * two are different more clearly.
 */
@Test
public void fromIterableShouldCreateAnObservableThatEmitsEachElementFromAnIterable() {
	
	List<String> sandwichIngredients = Arrays.asList("bread (one)", "bread (two)", "cheese", "mayo", "turkey",
			"lettuce", "pickles", "jalapenos", "Sriracha sauce");
	Observable<String> favoriteFoodsObservable = Observable.fromIterable(sandwichIngredients);
	TestObserver<String> testObserverIteratable = null; // TODO create new TestObserver and subscribe to favoriteFoodsObservable

	assertThat(testObserverIteratable.values()).hasSize(____);
	assertThat(testObserverIteratable.values()).containsAll(null);


	TestObserver<List<String>> testObserverForJust = new TestObserver<>();
	// TODO create obseverable for sandwichIngredients with just operator and subscribe testObserverForJust to it
	assertThat(testObserverForJust.values()).hasSize(1);
	assertThat(testObserverForJust.values()).contains(sandwichIngredients);
	/**
	 * ^^ As you can see here, fromIterable() & just() do very different things!
	 */
}
 
Example 4
Project: Learning-RxJava   File: Ch2_6.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    List<String> items =
            Arrays.asList("Alpha", "Beta", "Gamma", "Delta", "Epsilon");
    Observable<String> source = Observable.fromIterable(items);
    source.map(String::length).filter(i -> i >= 5)
            .subscribe(s -> System.out.println("RECEIVED: " + s));
}
 
Example 5
Project: wayf-cloud   File: DbExecutor.java   Source Code and License Vote up 5 votes
public <T> Observable<T> executeSelect(String query, Map<String, Object> arguments, Class<T> returnType) {
    // Add in limit and offset arguments by default. The limit is increased by 1 so that we can see if there is
    // more data for the client to paginate
    //
    // There should be a RequestContext in almost all cases. An exception would be a database call made prior
    // to the request being built like the one made to authenticated the API Token
    if (arguments.get(LIMIT) == null && RequestContextAccessor.get() != null) {
        arguments.put(LIMIT, RequestContextAccessor.get().getLimit() + 1);
    }

    if (arguments.get(OFFSET) == null && RequestContextAccessor.get() != null) {
        arguments.put(OFFSET, RequestContextAccessor.get().getOffset());
    }

    LOG.debug("Running query [{}] with values [{}]", query, arguments);

    List<T> results = namedParameterJdbcTemplate.query(query, arguments, new NestedFieldRowMapper(returnType, beanMapper));

    // If the results filled the limit + 1, there are more results to paginate through.
    if (results.size() == RequestContextAccessor.get().getLimit() + 1) {
        results.remove(results.size() - 1);

        if (RequestContextAccessor.get() != null) {
            RequestContextAccessor.get().setHasAnotherDbPage(Boolean.TRUE);
        }
    }

    return Observable.fromIterable(results);
}
 
Example 6
Project: vt-support   File: StorageImplTest.java   Source Code and License Vote up 5 votes
private static Observable<Entry> createEntries(int count) {
  List<Entry> entries = new ArrayList<>();
  for (int i = 0; i < count; i++) {
    entries.add(new Entry(22, i, i, "".getBytes()));
  }
  return Observable.fromIterable(entries);
}
 
Example 7
Project: Auto.js   File: StorageFileProvider.java   Source Code and License Vote up 5 votes
public Observable<PFile> getDirectoryFiles(PFile directory) {
    List<PFile> PFiles = getFilesFromCache(directory);
    if (PFiles == null) {
        return listFiles(directory);
    }
    return Observable.fromIterable(PFiles);
}
 
Example 8
Project: J-Chain   File: InOperator.java   Source Code and License Vote up 5 votes
private Function<Collection<T>, Observable<T>> toObservableFromIterable() {
    return new Function<Collection<T>, Observable<T>>() {
        @Override
        public Observable<T> apply(Collection<T> source) {
            return Observable.fromIterable(source);
        }
    };
}
 
Example 9
Project: rxjava2   File: ObservableErrorComplete.java   Source Code and License Vote up 5 votes
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 10
Project: wayf-cloud   File: IdentityProviderUsageRouting.java   Source Code and License Vote up 5 votes
public Observable<IdentityProviderUsage> readMyDeviceLocalHistory(RoutingContext routingContext) {
    LOG.debug("Received create IdentityProvider request");

    String globalId = RequestReader.getCookieValue(routingContext, RequestReader.DEVICE_ID);
    Device device = deviceFacade.read(new DeviceQuery().setGlobalId(globalId)).blockingGet();

    return Observable.fromIterable(identityProviderUsageFacade.buildRecentHistory(device));
}
 
Example 11
Project: rxjava2   File: StreamVsObservable.java   Source Code and License Vote up 5 votes
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 12
Project: dztools   File: HistoryFetchDate.java   Source Code and License Vote up 4 votes
private Observable<Long> countStreamForTickFetch(final long endTime) {
    final LongStream counter = LongStream
        .iterate(1, i -> i + 1)
        .map(count -> endTime - count * tickFetchMillis + 1);
    return Observable.fromIterable(counter::iterator);
}
 
Example 13
Project: wayf-cloud   File: DeviceAccessFacadeMockImpl.java   Source Code and License Vote up 4 votes
@Override
public Observable<DeviceAccess> filter(DeviceAccessQuery query) {
    return Observable.fromIterable(deviceAccessList);
}
 
Example 14
Project: Spring-5.0-Cookbook   File: DepartmentServiceImpl.java   Source Code and License Vote up 4 votes
@Override
public Observable<Department> getDeptsRx() {
	Observable<Department> depts= Observable.fromIterable(departmentDaoImpl.getDepartments());
	return depts;
}
 
Example 15
Project: Spring-5.0-Cookbook   File: EmployeeRxJavaServiceImpl.java   Source Code and License Vote up 4 votes
@Override
public Observable<Employee> getEmployeesRx() {
	Observable<Employee> publishedEmployees= Observable.fromIterable(employeeDaoImpl.getEmployees());
	return publishedEmployees;
}
 
Example 16
Project: spring-reactive-sample   File: RxJava2PostRepository.java   Source Code and License Vote up 4 votes
Observable<Post> findAll() {
    return Observable.fromIterable(DATA);
}
 
Example 17
Project: code-examples-android-expert   File: lessonC_BooleanLogicAndErrorHandling.java   Source Code and License Vote up 4 votes
/**
 * In this section we will learn about boolean logic we can apply to our
 * pipelines of data. Our first stop on the tour is takeWhile(), similar in
 * concept to the while loop you may already be familiar with.
 * http://reactivex.io/documentation/operators/takewhile.html
 * <p>
 * In this experiment, we will load elevators with passengers eager to reach
 * their destinations. One thing: Our elevator has a maximum capacity. If we
 * overload it, our passengers may be injured or even die! We will use
 * takeWhile to ensure no elevator is overloaded.
 */
@Test
public void takeWhileShouldEvaluateAnExpressionAndEmitsEventsUntilItReturnsFalse() {

	LessonResources.Elevator elevator = new LessonResources.Elevator();

	Observable<ElevatorPassenger> elevatorQueueOne = Observable
			.fromIterable(Arrays.asList(new ElevatorPassenger("Max", 168), new ElevatorPassenger("Mike", 234),
					new ElevatorPassenger("Ronald", 192), new ElevatorPassenger("William", 142),
					new ElevatorPassenger("Jacqueline", 114)));

	Observable<ElevatorPassenger> elevatorQueueTwo = Observable
			.fromIterable(Arrays.asList(new ElevatorPassenger("Randy", 320), new ElevatorPassenger("Jerome", 125),
					new ElevatorPassenger("Sally-Joe", 349), new ElevatorPassenger("Little Eli", 54)));

	/**
	 * the takeWhile operator evaluates an expression each time a new item
	 * is emitted in the stream. As long as it returns true, the Observable
	 * stream of data takeWhile operates on continues to emit more
	 * data/events.
	 *
	 * Riddle: Lets define our elevator rule: the total weight of all
	 * passengers aboard an elevator may not be larger than 500 pounds.
	 * How!?! Hint: Check out the Public methods available on
	 * LessonResources.Elevator and passenger!
	 */
	Predicate<ElevatorPassenger> elevatorPredicateRule = passenger -> (elevator.getTotalWeightInPounds() + passenger.mWeightInPounds < Elevator.MAX_CAPACITY_POUNDS);
	/**
	 * Now all we need to do is to plug in the rule in takeWhile()
	 */
	elevatorQueueOne.takeWhile(elevatorPredicateRule).doOnNext(elevator::addPassenger).subscribe(testObservable);
	// Ensure we have a positive weight
	assertThat(elevator.getPassengerCount()).isGreaterThan(____);
	// Elevator weight should not be larger than Elevator.MAX_CAPACITY_POUNDS
	assertThat(elevator.getTotalWeightInPounds()).isLessThan(____);
	assertThat(elevator.getPassengerCount()).isEqualTo(2);
	System.out.println("elevator stats: " + elevator);
	/**
	 * One of the great advantages of using RxJava is that functions become
	 * composable: we can easily reuse existing pieces of the pipeline by
	 * plugging them into other pipelines. takeWhile() accepts a predicate
	 * or rule for determining
	 */
	elevator.unload();

	elevatorQueueTwo.takeWhile(elevatorPredicateRule).subscribe(elevator::addPassenger);
	assertThat(elevator.getPassengerCount()).isGreaterThan(0);
	assertThat(elevator.getTotalWeightInPounds()).isLessThan(Elevator.MAX_CAPACITY_POUNDS);
	assertThat(elevator.getPassengerCount()).isEqualTo(2);

	/**
	 * a (secret) Extra Challenge! Using what we've learned of rxJava so
	 * far, how could we get a list of passengers from elevatorQueueTwo that
	 * didn't make it into elevator?
	 */
	testObservable = new TestObserver<>();


	//
	// TODO solve the challenge above
	//
	assertThat(testObservable.values()).hasSize(2);
}
 
Example 18
Project: Java-EX   File: NullableIterable.java   Source Code and License Vote up 4 votes
@Override
public Observable<T> observable() {
  return Observable.fromIterable(get());
}
 
Example 19
Project: wayf-cloud   File: DeviceIdentityProviderBlacklistFacadeMockImpl.java   Source Code and License Vote up 4 votes
@Override
public Observable<IdentityProvider> getBlacklistedIdentityProviders(Device device) {
    return Observable.fromIterable(blacklist);
}
 
Example 20
Project: RxJavaCollections   File: ObservableList.java   Source Code and License Vote up 2 votes
/**
 * Returns an observable which emits all items stored in the list, before completing.
 *
 * @return The {@link Observable} object.
 */
@Override
public Observable<E> observable() {
    return Observable.fromIterable(getList());
}