flatten_latest.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // This file is part of Desktop App Toolkit,
  2. // a set of libraries for developing nice desktop applications.
  3. //
  4. // For license and copyright information please follow this link:
  5. // https://github.com/desktop-app/legal/blob/master/LEGAL
  6. //
  7. #pragma once
  8. #include <rpl/producer.h>
  9. namespace rpl {
  10. namespace details {
  11. class flatten_latest_helper {
  12. public:
  13. template <
  14. typename Value,
  15. typename Error,
  16. typename Generator,
  17. typename MetaGenerator>
  18. auto operator()(producer<
  19. producer<Value, Error, Generator>,
  20. Error,
  21. MetaGenerator> &&initial) const {
  22. return make_producer<Value, Error>([
  23. initial = std::move(initial)
  24. ](const auto &consumer) mutable {
  25. auto state = consumer.template make_state<State>();
  26. return std::move(initial).start(
  27. [consumer, state](producer<Value, Error> &&inner) {
  28. state->finished = false;
  29. state->alive = lifetime();
  30. std::move(inner).start(
  31. [consumer](auto &&value) {
  32. consumer.put_next_forward(std::forward<decltype(value)>(value));
  33. }, [consumer](auto &&error) {
  34. consumer.put_error_forward(std::forward<decltype(error)>(error));
  35. }, [consumer, state] {
  36. if (state->finished) {
  37. consumer.put_done();
  38. } else {
  39. state->finished = true;
  40. }
  41. }, state->alive);
  42. }, [consumer](auto &&error) {
  43. consumer.put_error_forward(std::forward<decltype(error)>(error));
  44. }, [consumer, state] {
  45. if (state->finished) {
  46. consumer.put_done();
  47. } else {
  48. state->finished = true;
  49. }
  50. });
  51. });
  52. }
  53. private:
  54. struct State {
  55. lifetime alive;
  56. bool finished = false;
  57. };
  58. };
  59. } // namespace details
  60. inline auto flatten_latest()
  61. -> details::flatten_latest_helper {
  62. return details::flatten_latest_helper();
  63. }
  64. } // namespace rpl