jobs.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 { Map } from 'immutable'
  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: Map<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.has(state.jobId)) {
  27. jobs = jobs.delete(state.jobId);
  28. this.setState({ jobs });
  29. }
  30. return;
  31. }
  32. jobs = jobs.set(state.jobId, {
  33. name: state.name,
  34. message: state.message,
  35. abort: state.abort
  36. });
  37. this.setState({ jobs });
  38. }
  39. private started(job: Job.Info) {
  40. this.setState({
  41. jobs: this.latestState.jobs!.set(job.id, { name: job.name, message: 'Running...' })
  42. });
  43. }
  44. private completed(taskId: number) {
  45. if (!this.latestState.jobs!.has(taskId)) return;
  46. this.setState({
  47. jobs: this.latestState.jobs!.delete(taskId)
  48. });
  49. }
  50. constructor(context: Context, private type: Job.Type) {
  51. super(context, {
  52. jobs: Map<number, JobInfo>()
  53. });
  54. JobEvents.StateUpdated.getStream(this.context)
  55. .subscribe(e => this.updated(e.data));
  56. JobEvents.Started.getStream(this.context).pipe(
  57. filter(e => e.data.type === type))
  58. .subscribe(e => this.started(e.data));
  59. JobEvents.Completed.getStream(this.context)
  60. .subscribe(e => this.completed(e.data));
  61. }
  62. }