Run a Promise with RxJS, followed by a combination of the latest values

Apologies for bombarding you with more questions recently, but I'm really struggling to understand how everything links together.

Currently, a user is utilizing promise-based storage to store the names of feeds they wish to filter out. The Social Feeds widget displays the latest article from each feed that hasn't been hidden by the user.

I want to create a combination of the predefined list of feeds and the user's filtered feeds. To interact with the given API, I have to make multiple calls to the service to fetch each feed individually.

Once I've combined these feeds, my goal is to sequentially merge the observable produced by the getFeed utility method.

This is roughly what I intend to do, outlined in pseudocode:

/**
 * Retrieves the top items from all social media sources.
 * @param limit {number} Number of items per source.
 * @returns {Observable<SocialItem[]} Stream of SocialItem arrays.
 */
public getTopStories(limit: number = 1): Observable<SocialItem[]> {

    // Combine available feeds with those the user wishes to hide.
    const feedsToGet = this.storage.get('hiddenFeeds')
        .then(hiddenFeeds => _.union(FeedList, hiddenFeeds));

    // Retrieve and map feeds into an Observable<SocialItem[]>, adjusting the list as needed due to API limitations.
    // Utilize mergeMap to transform the array structure into a single array of SocialItems.
    const feeds$ = feedsToGet.map(feed => this.getFeed(feed).map(res = res ? res.slice(0, limit) : []).mergeMap(val => val));

    // Combine and return the streams
    return Observable.combineLatest(feed$);
}

Edit: Apologies for the fragmented code earlier.

Answer №1

Your example is close, but there's a timing issue with your manipulation process. Instead of using a Future of an Observable array, you should pass in an Observable array to combineLatest. This means you need to call combineLatest inside the promise handler. And don't forget to convert your

Promise<Observable<SocialItem[]>>
to Observable<SocialItem[]> by using another mergeMap.

public getTopStories(limit: number = 1): Observable<SocialItem[]> {
    // Merge available feeds with hidden ones.
    const feeds_future = this.storage.get('hiddenFeeds')
        .then(hiddenFeeds => Observable.combineLatest(_.map(
          _.union(FeedList, hiddenFeeds),
          feed => this.getFeed(feed).mergeMap(res => res ? res.slice(0, limit) : [])
        ))); // Promise<Observable<SocialItem[]>>

    return Observable.fromPromise(feeds) 
                     .mergeMap(v => v); 
}

Remember, the projection function in mergeMap lets you map values to Observables during the merging process itself, instead of mapping and then merging separately.

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

What is the best way to utilize jQuery to send JSON data and then parse it on a subsequent HTML page via the

My goal is to send JSON data through the URL to the next HTML page. While testing it on an emulator for a mobile app, I encountered an issue where the URL crashed instead of redirecting to the next page. Can someone help me understand why this might be hap ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Is it possible to include all visible content, even when scrolling, within the full page height?

My webpage contains content that exceeds the height of the window. I am looking for a way to retrieve the full height of my page using either jQuery or pure Javascript. Can anyone provide a solution? I have considered the following approach: $('body ...

insert information into a fixed-size array using JavaScript

I am attempting to use array.push within a for loop in my TypeScript code: var rows = [ { id: '1', category: 'Snow', value: 'Jon', cheapSource: '35', cheapPrice: '35', amazonSource ...

How can I nest a kendo-grid within another kendo-grid and make them both editable with on-cell click functionality?

I am facing an issue with my 2 components - trial1 (parent kendo-grid) and trial2 (child kendo-grid). Inside the template of trial1, I referenced the sub-grid component trial2. However, I am encountering an error where trial2 is not recognized inside trial ...

What is the approach to initiating a jquery function once HTML content is dynamically added through an AJAX call?

<div id="timeline"> <ul class="grow" id="grown"><li>One</li><li>Two</li><li>Three</li><li>Four</li><li>Five</li><li>Six</li><li>Seven</li><li>Eight< ...

Rearranging div placement based on the width of the screen

I am currently working on building a responsive website and I need two divs to switch positions depending on the screen width, both on initial load and when resizing. Despite my efforts in researching and trying various options, I have not been successful ...

Utilize React and Jest to handle errors by either mocking window values or resolving them

When my app attempts to inject environmental variables at runtime for docker using the window object, I encounter errors in my tests. The code snippet below shows the configuration: url config: declare const window: Window & typeof globalThis & ...

Unexpected Website Homepage (Vue / Javascript)

I am looking to display a different .vue file each time a visitor refreshes the Home page. Currently, I only have one page called Home.vue. I am attempting to randomly load either Home1.vue or Home2.vue with each refresh. { path: '/', name: ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

The functionality of vue-simple-alert is not compatible with Nuxt.js

I've been attempting to integrate the vue-simple-alert package into my Nuxt.js application, but unfortunately, it's not functioning as expected. Here are the steps I've followed: First, I installed and added the package to my package.json u ...

Is it possible to send a JSON array back to a Telegram bot using Node.js?

I'm facing a challenge with my telegram bot. I've developed the bot using node js with Java as the backend. The issue arises when a user inputs a category in the bot, which should then return a list of options under different categories. The prob ...

Is it possible to use Google Analytics to track touch interactions?

Is it feasible to utilize Google Analytics for tracking iOS touch events such as taps and swipes on browsers? Additionally, can it provide information on the x and y coordinates of where these events occur? ...

Customize Bootstrap Vue dropdown without any predefined styling options

After reviewing the documentation, I created a sample example utilizing the b-dropdown component: You can view the example here: https://codesandbox.io/s/6lhk6?file=/src/components/GenericItem.vue However, when I implemented the component in the code: &l ...

Vue.js and Firestore will only update variables that do not have empty string values

Modify the variables that are not empty strings const state = reactive({ birthNumber: '', phoneNumber: '', DoctorName: '', DoctorPhone: '', }) db.collection(state.user.uid).doc( ...

Adding property to an object retrieved from an API in a React application can be achieved effortlessly by utilizing the useState

How can I implement a toggle functionality for Bookmarked Meals on my Meal Recipe Website available at ? I am currently using the logic to set data.meals[0].bookmarked to true or false, but I want to use setState instead in order to rerender the page when ...

Does the success callback for AJAX operate synchronously?

Understanding that AJAX is asynchronous, a common question arises regarding the event execution within the success callback. Consider this scenario: $.ajax({ url : 'example.com', type: 'GET', success : (dataFromServer) { ...

I'm experiencing a flickering issue with my carousel when it reaches over 10,000 pixels during animation. Could this be related to a jQuery problem

After my carousel moves past 10000 pixels, it starts flickering through multiple elements. I'm utilizing jCarousel Lite: Could this be a jQuery-related issue? My initial assumption is that it may be specific to jCarousel Lite, but there doesn't ...

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

Ways to integrate an HTML document into a Python tkinter GUI window

I'm looking to integrate my HTML webpage project into a Python Tkinter window using Tkinter HTML view. However, when attempting to do so, the end result in the Python Tkinter window looks like this: what I'm getting. Contrary to that, here is wha ...