Skip to content

Instantly share code, notes, and snippets.

@hexadeciman
Created February 21, 2025 12:40
Show Gist options
  • Save hexadeciman/8b5ede03b3c16fdeaaa4b7ea07ccf2db to your computer and use it in GitHub Desktop.
Save hexadeciman/8b5ede03b3c16fdeaaa4b7ea07ccf2db to your computer and use it in GitHub Desktop.
C# RX Exercises

Mastering Reactive Extensions (Rx) in C#

This document provides a comprehensive set of exercises to help you become proficient with Reactive Extensions (Rx) in C#. The exercises are organized by difficulty level: Beginner, Intermediate, Advanced, and Expert. Each exercise includes a description and its real-world application.


Beginner Level

1. Create a Simple Observable and Subscribe to It

  • Description: Create an observable sequence of integers (e.g., 1 to 10) using Observable.Range and subscribe to it. Print each value to the console.
  • Real-World Application: Understanding the basics of observables and subscriptions, which are foundational in reactive programming.

2. Transform a Sequence Using Select

  • Description: Create an observable that emits numbers, then use Select to transform each number (e.g., multiply by 2).
  • Real-World Application: Data transformation, such as processing API responses or user input streams.

3. Filter a Sequence Using Where

  • Description: Create an observable that emits numbers and filter out even numbers using Where.
  • Real-World Application: Filtering data streams, such as filtering out invalid user inputs or irrelevant events.

4. Combine Two Observables with Merge

  • Description: Create two observables that emit different sequences of numbers and merge them into a single observable.
  • Real-World Application: Combining multiple event streams, such as merging logs from different sources.

5. Create a Timer Observable

  • Description: Use Observable.Timer to create an observable that emits a value after a delay and then completes.
  • Real-World Application: Scheduling tasks or delays in reactive systems.

Intermediate Level

6. Use Throttle to Handle Rapid Events

  • Description: Create an observable that emits values rapidly (e.g., every 100ms) and use Throttle to only process the last value emitted within a 1-second window.
  • Real-World Application: Debouncing high-frequency events, such as processing sensor data or rate-limiting API calls.

7. Use Buffer to Group Emitted Values

  • Description: Create an observable that emits values every second and use Buffer to group them into batches of 5 before processing.
  • Real-World Application: Batch processing, such as sending API requests in chunks or aggregating data over time.

8. Combine Latest Values from Two Observables with CombineLatest

  • Description: Create two observables that emit values at different intervals and use CombineLatest to combine their latest values into a tuple.
  • Real-World Application: Combining data streams, such as syncing metrics from different sensors.

9. Handle Errors with Catch

  • Description: Create an observable that throws an exception after emitting a few values. Use Catch to handle the error and continue with a fallback sequence.
  • Real-World Application: Handling errors gracefully in reactive systems, such as retrying failed API calls or providing default values.

10. Use Retry to Handle Transient Errors

  • Description: Create an observable that simulates a transient error (e.g., network failure) and use Retry to automatically retry the operation a fixed number of times.
  • Real-World Application: Implementing retry logic in network or database operations.

Advanced Level

11. Implement a Custom Operator

  • Description: Write a custom operator (e.g., RetryWithDelay) that retries a failing observable with a delay between retries.
  • Real-World Application: Extending Rx functionality for specific use cases, such as implementing custom retry logic for network requests.

12. Use GroupBy to Group Events

  • Description: Create an observable that emits a sequence of objects with a Category property. Use GroupBy to group the objects by category and process each group separately.
  • Real-World Application: Categorizing and processing grouped data, such as grouping logs by severity level or events by type.

13. Use Window to Create Time-Based Windows

  • Description: Create an observable that emits values every second and use Window to create time-based windows (e.g., 5-second windows). Process each window separately.
  • Real-World Application: Time-based processing, such as monitoring metrics or generating reports over fixed intervals.

14. Build a Reactive Pipeline for File System Monitoring

  • Description: Use FileSystemWatcher to create an observable that emits events when files are created, modified, or deleted in a directory. Process these events reactively.
  • Real-World Application: Building file monitoring tools or automating workflows based on file system changes.

15. Implement a Reactive Caching Mechanism

  • Description: Create an observable that fetches data from a slow source (e.g., a simulated database) and caches the results for subsequent subscribers. Use ReplaySubject to implement the caching.
  • Real-World Application: Optimizing performance by avoiding redundant computations or network calls.

Expert Level

16. Build a Reactive Log Processing System

  • Description: Create an observable that reads log entries from a file or stream and processes them reactively. Use GroupBy to group logs by severity (e.g., INFO, WARN, ERROR) and process each group separately.
  • Real-World Application: Building log monitoring and alerting systems.

17. Create a Reactive Task Scheduler

  • Description: Create a task scheduler that accepts tasks (as observables) and executes them reactively, ensuring that no more than a fixed number of tasks run concurrently.
  • Real-World Application: Managing workloads in distributed systems or background processing.

18. Simulate a Reactive IoT Sensor Network

  • Description: Create multiple observables that simulate data streams from IoT sensors (e.g., temperature, humidity). Use operators like CombineLatest, Buffer, and Window to process and analyze the data in real time.
  • Real-World Application: Building IoT platforms or real-time monitoring systems.

19. Build a Reactive Data Processing Pipeline

  • Description: Create a pipeline that reads data from a source (e.g., a CSV file), processes it reactively (e.g., filters, transforms, and aggregates), and writes the results to a target (e.g., another file or database).
  • Real-World Application: ETL (Extract, Transform, Load) processes in data engineering.

20. Implement a Rate-Limited API Client

  • Description: Create an observable that simulates API requests and use Throttle or Delay to ensure the requests are rate-limited (e.g., no more than 5 requests per second).
  • Real-World Application: Adhering to API rate limits in distributed systems.

21. Build a Reactive Event Bus

  • Description: Create a reactive event bus that allows different parts of an application to publish and subscribe to events. Use Subject or ReplaySubject to manage the event stream.
  • Real-World Application: Decoupling components in large applications, such as microservices or modular systems.

22. Integrate Rx with External Systems (e.g., Kafka, RabbitMQ)

  • Description: Create a reactive pipeline that consumes messages from a message broker (e.g., Kafka or RabbitMQ) and processes them reactively.
  • Real-World Application: Integrating reactive systems with external message queues for scalable and event-driven architectures.

23. Build a Real-Time Stock Ticker

  • Description: Build a stock ticker application that fetches stock prices from an API and updates the data stream reactively. Use operators like Throttle, Buffer, and CombineLatest to process and display the data efficiently.
  • Real-World Application: Real-time data processing, such as financial applications or live dashboards.

24. Implement a Reactive Circuit Breaker

  • Description: Create a circuit breaker mechanism that monitors an observable for errors and stops further processing if the error rate exceeds a threshold. Use Window and Count to calculate error rates.
  • Real-World Application: Improving system resilience by preventing cascading failures in distributed systems.

25. Build a Reactive Workflow Engine

  • Description: Create a workflow engine that executes a series of tasks reactively, where each task depends on the output of the previous one. Use operators like SelectMany and Concat.
  • Real-World Application: Automating complex workflows in distributed systems or business processes.

Tips for Mastery

  1. Start Small: Focus on understanding the basics of observables, subscriptions, and operators like Select and Where.
  2. Experiment: Modify the exercises to explore different operators and scenarios.
  3. Combine Concepts: Build projects that combine multiple concepts, such as a reactive log processor or a task scheduler.
  4. Optimize Performance: Pay attention to memory usage and performance when working with large or infinite streams.
  5. Integrate with Systems: Practice integrating Rx with external systems like databases, message brokers, or file systems.

By completing these exercises, you’ll gain deep expertise in Rx and be well-equipped to build robust and scalable reactive systems in C#.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment