安裝
ReactiveX/RxCpp: Reactive Extensions for C++ (github.com)
在github下載源碼,源碼都是頭文件,將 ~/Rx/v2/src/rxcpp 整個目錄拷貝到工程目錄,應用中包含頭文件即可,無需編譯庫文件。
第一個程序

#include <iostream> #include <thread> #include <memory> #include <atomic> #include <chrono> #include "rxcpp/rx.hpp" namespace Rx { using namespace rxcpp; using namespace rxcpp::sources; using namespace rxcpp::operators; using namespace rxcpp::util; using namespace rxcpp::schedulers; } using namespace Rx; int main(int argc, char const *argv[]) { auto keys = observable<>::create<int>( [](subscriber<int> dest){ for (;;) { int key = std::cin.get(); if ('q' == key) { dest.on_completed(); break; } dest.on_next(key); } }); keys.subscribe([](int key){ std::cout << "User types key: " << (char)key << std::endl; }, [](){ std::cout << "User entered 'q' to exit." << std::endl; }); return 0; }
附上Makefile

CXXFLAGS += -I./ -std=c++11 SRC := $(wildcard ./*.cpp) OBJ := $(SRC:%.cpp=%.o) test_rxcpp: $(OBJ) $(CC) -o $@ $^ -lpthread -lm -ldl -lstdc++ strip $@ all: test_rxcpp clean: @rm -f test_rxcpp @rm -f $(OBJ)
運行結果:
s User types key: s User types key: g User types key: g User types key: t User types key: t User types key: q User entered 'q' to exit.
程序只是簡單讀取用戶輸入的字符並將它們一個個打印出來,直到用戶輸入'q',才退出。
它創建了一個被觀察者keys,用於監控用戶輸入,並將輸入數據發送出去,給后級的觀察者,這里觀察只是簡單的打印一下接收到的字符。
這里為啥有字符沒打印出來呢?那是個換行符,讓我們來濾掉它:

keys.filter([](int key) { return key != '\n'; }).subscribe([](int key){ std::cout << "User types key: " << (char)key << std::endl; }, [](){ std::cout << "User entered 'q' to exit." << std::endl; });
運行結果:
sg User types key: s User types key: g r User types key: r t User types key: t q User entered 'q' to exit.
filter是RX中operator中的一種,返回true的數據才會被送到后一級。
若是有必要,它的后級還可以繼續鏈上其他操作符,這樣,數據就從被觀察者,流經一系列過濾、轉換等操作,最后被觀察者所接收。
這種操作,以及其他operator我們將在后面的學習中接觸到。
初接觸這種編程方式,可能會一時難以適應。但沒關系,學習新東西總有這么個過程。
網絡上找到的關於RxCpp的資料不多,實用的更少,后續盡量多總結一下。
下面的兩個鏈接,感覺對於理解反應性編程幫助挺大的,感謝作者的分享!
ReactiveX - 隨筆分類 - zwvista - 博客園 (cnblogs.com)
以及官網文檔