rxpoweredup
Version:
A Typescript RxJS-based library for controlling LEGO Powered UP hubs & peripherals.
55 lines (54 loc) • 1.74 kB
JavaScript
import { BehaviorSubject, EMPTY, Subject, filter, from, of, switchMap, take } from 'rxjs';
export class TaskWithResponse {
message;
responsesStream;
result;
completed = new BehaviorSubject(false);
earlyResponseCaptureSubscription;
constructor(message, responsesStream) {
this.message = message;
this.responsesStream = responsesStream;
this.result = new Subject();
}
discard() {
this.result.complete();
}
accept(visitor) {
visitor.visitTaskWithResponse(this);
}
dispose() {
this.earlyResponseCaptureSubscription?.unsubscribe();
}
emitError(error) {
this.result.error(error);
this.earlyResponseCaptureSubscription?.unsubscribe();
this.completed.complete();
}
execute(channel) {
this.earlyResponseCaptureSubscription?.unsubscribe();
this.earlyResponseCaptureSubscription = this.responsesStream
.pipe(take(1))
.subscribe({
next: (response) => {
this.result.next(response);
this.result.complete();
this.completed.next(true);
},
error: (error) => {
this.result.error(error);
this.result.complete();
this.completed.next(true);
},
complete: () => {
this.result.complete();
this.completed.next(true);
},
});
if (this.completed.value) {
return EMPTY;
}
else {
return of(null).pipe(switchMap(() => from(channel.sendMessage(this.message))), switchMap(() => this.completed), filter((v) => v), take(1));
}
}
}