Unusual Outcome from Observable.interval() Combined with flatMap()

When attempting to chain Observable.interval() with .flatMap(), I encountered what seems to be unexpected behavior.

Below is the code snippet I am using (with Angular 2):

Observable.interval(1500)
  .scan((numArr:any[], curr:any, i:number) => {
    numArr.push(i);
    return numArr;
  }, [])
  .do(arr => console.log('interval value', arr))
  .flatMap(numArr => {
    return Observable.interval(500)
      .map(i => {
        numArr.forEach((el, i, arr) => {
          arr[i] += 1;
        })
        return numArr;
      })
  }).subscribe(res => console.log('final value', res));

The current output I am receiving:

interval value [0]
final value [1]
final value [2]
interval value [2, 1]
final value [3, 2]
final value [4, 3]
final value [5, 4]
final value [6, 5]
final value [7, 6]
interval value [7, 6, 2]
final value [8, 7, 3]
final value [9, 8, 4]
final value [10, 9, 5]
....

I expect to receive 3 values between each "interval value" cycle instead of getting a larger list every time the interval emits a value. Why is this happening and how can it be resolved?

My goal is to increment by 1 for each value in the array emitted by the first Observable.interval() every 500ms. Essentially, the desired result is:

interval value [0]
final value [1]
final value [2]
final value [3]
interval value [3, 1]
final value [4, 2]
final value [5, 3]
final value [6, 4]
interval value [6, 4, 1]
final value [7, 5, 2]
final value [8, 6, 3]
final value [9, 7, 4]
....

Any assistance would be greatly appreciated. Thank you.

Answer №1

This is an intriguing issue. It's possible that I may not have a complete grasp of your intentions here, especially with the complications arising from mutating the original array in the flatMap function. Despite that, my suggestion would be to approach it as follows:

The observable generated within flatMap doesn't stop executing - it continues incrementing values in numArr even after receiving another interval value. This results in every value in numArr being incremented twice every 500ms after two interval values, thrice after three interval values, and so forth. To achieve the desired outcome (increment all values thrice, then add a new value to the array, at intervals of 500ms), you can limit the Observable in flatMap to just three iterations using .take(3).

You could also obtain the same result by utilizing concatMap instead of flatMap, as it concatenates the observables created inside (one observable runs sequentially, while the next one starts after the previous completes) rather than merging them. However, I recommend sticking with take(3) for your solution.

Answer №2

To avoid any pending interval observables, it is recommended to replace the second flatMap() with a switchMap().

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

Storing various values in the database using CakePHP 3

While working on receiving data, I encountered an issue where the saved time in the database is different from what was input. For example, when I send 8:00 pm, it gets saved as 12:00 am due to a +4 hour difference. When I receive data from a form and che ...

Dealing with incoming data in a yii2 RESTful service

When sending an array using $http post, I follow this approach: var results = services.transaction('orderdetails/insert', {customer_id: $scope.order.customer_id, data: $scope.orderDetail}); The variable $scope.orderdetail ...

Invalid preflight response (redirect) error

I am a beginner in utilizing Laravel and Lumen frameworks for my projects. Currently, I am working on my first project using Lumen and attempting to create an API call from Angular. Below is the Angular code snippet: app.controller('ListCtrl', ...

Issues with Angular authentication: HTTP POST request not being sent

UPDATE: I had a small oversight with my submit button placement, but it's all sorted out now (turns out the request wasn't sent because my function wasn't called, a classic mistake). Furthermore, the reason why authentication always succ ...

troubleshooting problems with AJAX calls and routing in Angular

I am a beginner with Angular and I recently completed a tutorial on Single Page Application development using templates imported from PHP files, along with Resource and Route modules. Below is the JavaScript code from my project: (function(){ var app ...

Using Ionic with Ubuntu to easily connect to MySQL and PHPMyAdmin

element, My current project involves creating a mobile app using Ionic on Ubuntu. I have successfully installed and configured phpmyadmin, which is now operational at http://localhost/phpmyadmin. Can someone guide me on how to configure Ionic to connect ...

The perfect combination: Symfony2 and AngularJS working together

Currently, I have been working on a web app that utilizes Symfony2 and recently integrated AngularJS. Within this app, there is an input field where users can filter products by name. The issue arises when it comes to querying the database in PHP and passi ...

Retrieve the result set rows and store them in an array as individual objects

I'm attempting to fetch data from a MySQL database using Angular and PHP. My Angular code looks like this: $http({ url: "http://domain.com/script.php", method: "POST", headers: {'Content-Type': 'applica ...

Strategies for optimizing polling of mySQL database using $http.get

** ANGULAR 1.X ** Hey there! I'm currently seeking assistance in making this $http.get function asynchronous. Currently, my workaround involves using a setInterval on the displayData scope. However, this solution is not efficient as it consumes a lot ...

Integration of AngularJS with PHP for Seamless User Authentication

As a newcomer to angularjs, I find the Login Process a bit confusing. Every time I log in, I'm automatically redirected to a specific page that is already set in the code. I just want a simple check to see if the user is logged in. If they are, then ...

No data found in php://input when accessing Azure

Having an issue with posting a complex JSON object to my Azure IIS server running PHP 5.4 using AngularJS: var request = $http({ method: "post", url: "/php/mail.php", data: $scope.contactForm, headers: { 'Content-Type': & ...

Expanding/Combining entities

I'm facing an issue while trying to Extend/Push/Merge an object using AngularJS. The problem arises when I attempt to extend the object, as it adds a new object with an Index of 0 and subsequent additions also receive the same index of 0. //Original ...

Struggling to make $http post requests to PHP using Angular

I am experiencing difficulties in transferring data to my PHP file after decoding Json, resulting in an error. I need assistance in identifying where I have made a mistake. app.js $scope.formPost = function(){ $http.post('sendmail.php' ...

AngularJS $http.get request failing to retrieve data

I've been delving into AngularJS lately, but I'm having trouble displaying the data from my MySQL database on the view. Here's the code snippets I'm working with: todoController.js angular .module('todoApp') .control ...

Is it advisable to load 10,000 rows into memory within my Angular application?

Currently, I am in the process of creating a customer management tool using Angular.js that will allow me to directly load 10,000 customers into the $scope. This enables me to efficiently search for specific data and manipulate it without the need for serv ...

Incorporating dynamic images into Laravel using Angular

I am currently trying to dynamically input the src value of an image using Angular. Below is the code I have written : HTML : <div ng-app="myApp" ng-controller="MyCtrl"> <img src="{{asset('assets/img/'.'/'. @{{ item.name ...

Tips for structuring a SQL query result in an AngularJS application

Forgive me if this code is not up to par with the best standards, as I am still relatively new to angular.js. The issue I am facing is that when the data is returned from my query, it appears as a block of text. Despite using echo statements in search.php ...

Encountering an issue with the Ionic Serve Command

Currently, I am working on creating a mobile app with the Ionic framework. After running the command ionic server, I encountered this error: /deps/uv/src/unix/stream.c:494: uv__server_io: Assertion `events == 1' failed Any suggestions or assistanc ...

Sending post parameters from Angular and receiving JSON data from PHP using $http

Exploring the world of Angular and delving into the realm of $http, I find myself faced with a perplexing challenge: How to post parameters using $http (necessary for PHP to execute the call) Retrieve a JSON response from that call Here's what I&ap ...

Designing motion graphics for a browser game

As I delve into learning about Node.js, Angular.js, Socket.io, and Express.js, my current project involves creating a multiplayer poker game like Texas Hold 'Em. However, despite spending a considerable amount of time browsing the internet, I have bee ...