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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Description: Create an observable that emits a sequence of objects with a
Category
property. UseGroupBy
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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Description: Create multiple observables that simulate data streams from IoT sensors (e.g., temperature, humidity). Use operators like
CombineLatest
,Buffer
, andWindow
to process and analyze the data in real time. - Real-World Application: Building IoT platforms or real-time monitoring systems.
- 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.
- Description: Create an observable that simulates API requests and use
Throttle
orDelay
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.
- Description: Create a reactive event bus that allows different parts of an application to publish and subscribe to events. Use
Subject
orReplaySubject
to manage the event stream. - Real-World Application: Decoupling components in large applications, such as microservices or modular systems.
- 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.
- Description: Build a stock ticker application that fetches stock prices from an API and updates the data stream reactively. Use operators like
Throttle
,Buffer
, andCombineLatest
to process and display the data efficiently. - Real-World Application: Real-time data processing, such as financial applications or live dashboards.
- 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
andCount
to calculate error rates. - Real-World Application: Improving system resilience by preventing cascading failures in distributed systems.
- 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
andConcat
. - Real-World Application: Automating complex workflows in distributed systems or business processes.
- Start Small: Focus on understanding the basics of observables, subscriptions, and operators like
Select
andWhere
. - Experiment: Modify the exercises to explore different operators and scenarios.
- Combine Concepts: Build projects that combine multiple concepts, such as a reactive log processor or a task scheduler.
- Optimize Performance: Pay attention to memory usage and performance when working with large or infinite streams.
- 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#.