All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.adito.util.reactive.ObservableCollectors Maven / Gradle / Ivy

package de.adito.util.reactive;

import io.reactivex.rxjava3.core.Observable;
import org.jetbrains.annotations.NotNull;

import java.util.*;
import java.util.function.*;
import java.util.stream.Collector;

/**
 * @author w.glanzer, 04.12.2018
 */
public class ObservableCollectors
{

  private ObservableCollectors()
  {
  }

  /**
   * Returns a collector which combines an Stream of Observables to one observable.
   * It is combined via Observable.combineLatest()
   *
   * @return the Collector
   */
  @NotNull
  public static  Collector, ?, Observable>> combineToList()
  {
    return _combine(pData -> {
      List values = new ArrayList<>();
      for (Object data : pData)
        values.add((T) data);
      return values;
    });
  }

  /**
   * Returns a collector which combines an Stream of Observables to one observable.
   * It is combined via Observable.combineLatest()
   *
   * @return the Collector
   */
  @NotNull
  public static  Collector>, ?, Observable>> combineOptionalsToList()
  {
    return _combine(pData -> {
      List values = new ArrayList<>();
      for (Object data : pData)
        ((Optional) data).ifPresent(values::add);
      return values;
    });
  }

  /**
   * Returns a collector which combines an Stream of Observables to one observable.
   * It is combined via Observable.combineLatest()
   *
   * @return the Collector
   */
  @NotNull
  public static  Collector>, ?, Observable>> combineListToList()
  {
    return _combine(pData -> {
      List values = new ArrayList<>();
      for (Object data : pData)
        values.addAll(((List) data));
      return values;
    });
  }

  /**
   * Returns an Collector which combines Observables to one Observable with a value-List
   *
   * @param pFn   Function, which combines the Input-Values to a List of output-Values
   * @param   INPUT-Value-Type
   * @param  OUTPUT-Value-Type
   * @return the Collector, not null
   */
  @NotNull
  private static  Collector, ?, Observable>> _combine(@NotNull Function> pFn)
  {
    return Collector.of((Supplier>>) ArrayList::new, ArrayList::add, (pList1, pList2) -> {
      ArrayList> copy = new ArrayList<>(pList1);
      copy.addAll(pList2);
      return copy;
    }, pList -> {
      if (pList.isEmpty())
        return Observable.just(Collections.emptyList());
      return Observable.combineLatest(pList, pFn::apply);
    });
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy