首页 > 其他分享 > rxjs 实现动态异步调度系统

rxjs 实现动态异步调度系统

时间:2023-02-07 19:57:40浏览次数:45  
标签:addTask resolve const 异步 request 调度 task rxjs new

 

  • 通过mergemap操作符: 实现任务池的限制,
  • 通过defer操作符: 延迟创建可观察对象实现 异步 task的队列等待。

最终输出结果2,1,3,4 符合预期 

import React, { useState, useEffect } from 'react';

import { Subject, interval, fromEvent, of, from, defer } from 'rxjs';
import { map, scan, startWith, switchMap, takeUntil, takeWhile, mergeMap, delay } from 'rxjs/operators';

const taskSubject = new Subject();
const concurrentLimit = 2;

const source = taskSubject.pipe(
  mergeMap((task) => defer(() => from(task())), concurrentLimit),
);

source.subscribe((val) => console.log(val));

const addTask = (task) => {
  taskSubject.next(task);
};

const Elevator = () => {
  return (
    <div onClick={() => {
      addTask(() => new Promise((resolve) => setTimeout(() => resolve({ data: 'request 1' }), 3000)));
      addTask(() => new Promise((resolve) => setTimeout(() => resolve({ data: 'request 2' }), 1000)));
      addTask(() => new Promise((resolve) => setTimeout(() => resolve({ data: 'request 3' }), 100)));
      addTask(() => new Promise((resolve) => setTimeout(() => resolve({ data: 'request 4' }), 1000)));
    }}
    >dd


    </div>

  );
};

export default Elevator;

  

标签:addTask,resolve,const,异步,request,调度,task,rxjs,new
From: https://www.cnblogs.com/breakdown/p/17099601.html

相关文章