-
Create the Observables:
- Create an observable (
clickObservable) that emits data whenever a click event occurs.
- Create another observable (
dataStream) that streams data continuously.
-
Use combineLatest Operator:
- Use the
combineLatest operator to combine the two observables. combineLatest takes multiple observables as input and emits a tuple containing the latest values from each observable whenever any of them emit.
-
Subscribe to the Combined Observable:
- Subscribe to the combined observable to receive the tuples containing the latest values from both observables.
Here's an example code that demonstrates how to combine the click observable and the data stream using combineLatest:
import { Observable, combineLatest } from 'rxjs';
// Create the click observable
const clickObservable = Observable.fromEvent(document, 'click');
// Create the data stream observable
const dataStream = Observable.interval(1000).map(val => `Data ${val}`);
// Combine the two observables
const combinedObservable = combineLatest(clickObservable, dataStream);
// Subscribe to the combined observable
combinedObservable.subscribe(([clickEvent, data]) => {
console.log(`Click event: ${clickEvent}`);
console.log(`Latest data: ${data}`);
});
In this example, when a click event occurs, the combineLatest operator will emit a tuple containing the click event and the latest data from the data stream. You can then subscribe to the combined observable to receive these tuples and perform the desired operations.