jobs.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * Adapted from LiteMol
  5. * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
  6. */
  7. import produce from 'immer'
  8. import { filter } from 'rxjs/operators';
  9. import { Controller } from '../controller'
  10. import { JobEvents } from '../../event/basic';
  11. import { Context } from '../../context/context';
  12. import { Job } from '../../service/job';
  13. export interface JobInfo {
  14. name: string;
  15. message: string;
  16. abort?: () => void
  17. }
  18. export interface JobsState {
  19. jobs: { [k: number]: JobInfo }
  20. }
  21. export class JobsController extends Controller<JobsState> {
  22. private updated(state: Job.State) {
  23. let isWatched = state.type === this.type;
  24. let jobs = this.latestState.jobs!;
  25. if (!isWatched) {
  26. if (jobs[state.jobId] !== undefined) {
  27. jobs = produce(jobs, _jobs => { delete _jobs[state.jobId] });
  28. this.setState({ jobs });
  29. }
  30. return;
  31. }
  32. jobs = produce(jobs, _jobs => {
  33. _jobs[state.jobId] = {
  34. name: state.name,
  35. message: state.message,
  36. abort: state.abort
  37. };
  38. })
  39. this.setState({ jobs });
  40. }
  41. private started(job: Job.Info) {
  42. this.setState({
  43. jobs: produce(this.latestState.jobs!, _jobs => {
  44. _jobs[job.id] = { name: job.name, message: 'Running...' }
  45. })
  46. });
  47. }
  48. private completed(taskId: number) {
  49. if (!this.latestState.jobs![taskId]) return;
  50. this.setState({
  51. jobs: produce(this.latestState.jobs!, _jobs => { delete _jobs[taskId] })
  52. });
  53. }
  54. constructor(context: Context, private type: Job.Type) {
  55. super(context, {
  56. jobs: {}
  57. });
  58. JobEvents.StateUpdated.getStream(this.context)
  59. .subscribe(e => this.updated(e.data));
  60. JobEvents.Started.getStream(this.context).pipe(
  61. filter(e => e.data.type === type))
  62. .subscribe(e => this.started(e.data));
  63. JobEvents.Completed.getStream(this.context)
  64. .subscribe(e => this.completed(e.data));
  65. }
  66. }