Reactive Extensions

Reactive Extensions(Rx) 는 Observer 패턴, Iterator 패턴, 함수형 프로그래밍의 조합이다.

  • Procedure
public static Iterable<Book> getAuthorsBooks(Collection<Book> allBooks, String author) {
    List<Book> result = new ArrayList();
    for (Book book: allBooks) {
        if (author.equals(book.author)) {
            result.add(book);
        }    
    }
    return result;
}
  • Functional
public static Iterable<Book> getAuthorsBooks(Collection<Book> allBooks, String author) {
    return allBooks.stream()
        .filter(book -> author.equals(book.author))  
        .collect(Collectors.toList());
}
  • Reactive
public static Observable<Book> getAuthorsBooks(Collection<Book> allBooks, String author) {
    return Observable.from(allBooks).filter(book -> author.equals(book.author));
}

Observable

Event Iterable(pull) Observable(push)
retrieve data T next() onNext(T)
discover error throws Exception onError(Exception)
complete !hasNext() onCompleted()

ReactiveX, many instructions may execute in parallel and their results are later captured, in arbitrary order, by “observers.” Rather than calling a method, you define a mechanism for retrieving and transforming the data, in the form of an “Observable,” and then subscribe an observer to it, at which point the previously-defined mechanism fires into action with the observer standing sentry to capture and respond to its emissions whenever they are ready.

References

  • Reactive Systems Explained / Grace Jansen & Peter Gollmar 저 / O'REILLY