What initiates the activation of a hot observable series within reactive statements?

Can someone explain to me when the mouse move observable is activated in this example from RxJS on GitHub? What exactly triggers it to start sampling the mousemove event?

I initially thought that subscribing would begin the sequences for all observables in mousedrag, but it doesn't appear to be the case. There are mousemove events happening before mousedown, but they don't seem to be utilized.

var dragTarget = document.getElementById('dragTarget');

// Obtaining the three main events
var mouseup   = Rx.Observable.fromEvent(dragTarget, 'mouseup');
var mousemove = Rx.Observable.fromEvent(document,   'mousemove');
var mousedown = Rx.Observable.fromEvent(dragTarget, 'mousedown');

var mousedrag = mousedown.flatMap(function (md) {
    // calculating offsets on mouse down
    var startX = md.offsetX, startY = md.offsetY;

    // Calculating delta with mousemove until mouseup
    return mousemove.map(function (mm) {
        mm.preventDefault();

        return {
            left: mm.clientX - startX,
            top: mm.clientY - startY
        };
    }).takeUntil(mouseup);
});

// Updating position
var subscription = mousedrag.subscribe(function (pos) {          
    dragTarget.style.top = pos.top + 'px';
    dragTarget.style.left = pos.left + 'px';
});

I'd appreciate any insights on this matter.

Answer №1

I absolutely love using RxJS because of how it addresses the question you asked!

...what triggers the mouse move observable to start sampling the mousemove event?

In the case of the mouse move observable, it is "activated" (or "subscribed to") precisely when it is needed and then disposed of promptly when no longer required! In the example scenario provided, the event binding occurs after

return mousemove.map(function (mm) { ... })

is executed (which happens only after mousedrag.subscribe is called).

Upon inspecting the code for observable.map, one can observe that the parent (mousemove in this instance) is subscribed to, and the function within map is invoked inside its onNext event.

Diving deeper into the rabbit hole, one would stumble upon Observable.fromEvent, which is the specific location where event listening takes place. Nonetheless, for most practical purposes, the subscribe method within the observable.map function is where the activation occurs.

Ultimately, the .takeUntil(mouseup) method at the end of the `.map` chain is responsible for cleaning up and disposing of everything. The `onNext` for that observable will handle the disposal of the previous subscription, which, in this example, would be the `.map` function or the event listener. Once a `mouseup` event transpires, the subscription for `mousemove` is deactivated and disposed of.

To test this out, you can set breakpoints at var subscription = ..., return mousemove.map, and mm.preventDefault();. They should be triggered in the following sequence:

  1. var subscription = ...
  2. Mouse down
  3. return mousemove.map
  4. mouse move
  5. mm.preventDefault();
  6. mouse up
  7. mouse move, without breaking

If you need further clarification or have any questions about what I've mentioned, please feel free to ask. Good luck with your experiments!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Establishing a small boutique utilizing Vue.observable for property getters

I am currently importing the createStore function into a store.js file and passing an object with state properties and mutation functions as an argument, which is working well. createStore.js import Vue from 'vue' function createStore({ state, ...

The Tooltip fails to display my content when hovered over for the first time, but it appears on the second attempt

Here is the code snippet: <a href="", class="cancel-invitation-from-other" title="Close" onmouseover = "show_bookclub_book_tooltip('Decline invitation','cancel-invitation-from-other');" data-placement="top"></a> and this i ...

Personalizing the text of an item in a v-select interface

Can the item-text be customized for the v-select component? I am interested in customizing each item within the v-select dropdown, similar to this example: :item-text="item.name - item.description" ...

Make changes to the HTML file by directly using Jquery or JavaScript

Allow me to elaborate on my current objective. I have an HTML file that requires direct content updates. Specifically, I am working with elements sharing the 'id=test'. My goal is to dynamically update all elements with unique IDs such as ' ...

Customize Tab indicator styling in Material-UI

Currently, I am attempting to customize the MUI tab by changing the indicator from a line to a background color. Through my research, I discovered that using TabIndicatorProps and setting a style of display:none eliminates the indicator completely. However ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

Dialogue Inventory System

I am in the process of developing a conversation system that includes a page where users can view all of their conversations and select which one they want to reply to. The layout is structured as follows: You can view an image of the layout here. The co ...

Activate a timer as soon as the page is first loaded. The timer must continue running from the initial load even if the user leaves

Looking to implement a time-limited offer on the first stage of our checkout process. The timer should start at 5 minutes when the page loads and continue counting down even if the user leaves the page and returns. Has anyone come across a script that can ...

Verify if Javascript is enabled

Can I determine if the browser supports or has Javascript enabled? If not supported, my goal is to direct the user to a more user-friendly error page. My current tech stack includes jQuery and PHP Zend Framework. ...

Error occurs when passing a service as a parameter to a controller in AngularJS

After adding 'loginService' as a parameter to the controller in order to reference the service I want to use, I encountered an error that caused the rest of my angular functions to stop working. app.controller('loginController', functi ...

A guide on accessing header response information in Vue.js

Currently, I am operating on my localhost and have submitted a form to a remote URL. The process unfolds in the following sequence: Submission of a form from localhost Being redirected to a remote URL Sending a response back from the Remote URL to localh ...

Unleashing the Power of the "OR" Operator in Form Field Validation

The custom JavaScript function FormQuote_Validator is used to validate form fields. It should return the value "TRUE" and display an alert message if all three input fields are submitted without any numbers; otherwise, it should return the value "FALSE". ...

Using JavaScript to create an array within an object and adding new elements to the array

I'm just beginning to learn programming and experimenting with React. I have a function called addComment that is triggered when a user adds a comment to a news article. At this point, I need to create a property called comments (an array) and either ...

Establishing connections between check boxes and text entry fields and dynamically updating the data within them

I am attempting to connect a checkbox with a text input so that the value inside the input field can be updated. The issue I'm facing is how to appropriately update the value when the checkbox is checked. For instance, my goal is to display the status ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

show information in a continuous manner using javascript

I'm having trouble extracting the latitude and longitude coordinates of markers to display them on the map. Even though my parser.php file successfully retrieves data from the database, I am struggling to format it into JavaScript. Any suggestions? & ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...

Problem with a for loop: retrieve only the final item

Using the fileReader to read the content of selected files and appending it to the DOM creates a paragraph element for each file. However, when attempting to store each file's content in local storage, only the last item is being saved. What could be ...