use RXJS to unsubscribe when a Subject emits specific value - rxjs

I think I should leverage RXJS for a particular use case. The use case is that I have a subscription that I want to live until a certain value is emitted from a Subject somewhere else.
Eg:
// The sub to unsub when a certain <value> is emitted from a Subject elsewhere.
this.someObservable.subscribe(() => ...)
// Somewhere in the code far, far away, this should kill the subscription(s) that cares about <value>
this.kill.next(<value>)
My go to approach to handle this is caching the subscriptions and then unsubscribing when this.kill.next(<value>) with the relevant <value> is called. Though, that is the imperative approach and feels like it can be done better via takeWhile or some other such technique. Perhaps I might need to merge someObservable with kill Subject ?
How can I leverage RXJS to handle this?

takeUntil is the operator you want
this.someObservable.pipe(
takeUntil(this.kill.pipe(filter(val => val === killValue)))
).subscribe(() => ...)
Once the kill observable emits the killValue it will pass the filter and emit to the takeUntil which unsubscribes the stream.
const { timer, fromEvent, Subject } = rxjs;
const { takeUntil, filter } = rxjs.operators;
const kill$ = new Subject();
kill$.subscribe(val => {
console.log(val);
});
timer(500, 500).pipe(
takeUntil(kill$.pipe(filter(val => val === 'kill')))
).subscribe(val => {
console.log(val);
});
document.getElementById('rnd').addEventListener('click', () => {
kill$.next(Math.random());
});
document.getElementById('kill').addEventListener('click', () => {
kill$.next('kill');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.6.2/rxjs.umd.min.js"></script>
<button id="rnd">Emit random</button>
<button id="kill">Emit kill</button>

Related

Implement a loop logic within an rxjs pipe

I have a class, QueueManager, which manages some queues.
QueueManager offers 3 APIs
deleteQueue(queueName: string): Observable<void>
createQueue(queueName: string): Observable<string>
listQueues(): Observable<string>: Observable`
deleteQueue is a fire-and-forget API, in the sense that it does not return any signal when it has completed its work and deleted the queue. At the same time createQueue fails if a queue with the same name already exists.
listQueues() returns the names of the queues managed by QueueManager.
I need to create a piece of logic which deletes a queue and recreates it. So my idea is to do something like
call the deleteQueue(queueName) method
start a loop calling the listQueues method until the result returned shows that queueName is not there any more
call createQueue(queueName)
I do not think I can use retry or repeat operators since they resubscribe to the source, which in this case would mean to issue the deleteQueue command more than once, which is something I need to avoid.
So what I have thought to do is something like
deleteQueue(queueName).pipe(
map(() => [queueName]),
expand(queuesToDelete => {
return listQueues().pipe(delay(100)) // 100 ms of delay between checks
}),
filter(queues => !queues.includes(queueName)),
first() // to close the stream when the queue to cancel is not present any more in the list
)
This logic seems actually to work, but looks to me a bit clumsy. Is there a more elegant way to address this problem?
The line map(() => [queueName]) is needed because expand also emits values from its source observable, but I don't think that's obvious from just looking at it.
You can use repeat, you just need to subscribe to the listQueues observable, rather than deleteQueue.
I've also put the delay before listQueues, otherwise you're waiting to emit a value that's already returned from the API.
const { timer, concat, operators } = rxjs;
const { tap, delay, filter, first, mapTo, concatMap, repeat } = operators;
const queueName = 'A';
const deleteQueue = (queueName) => timer(100);
const listQueues = () => concat(
timer(1000).pipe(mapTo(['A', 'B'])),
timer(1000).pipe(mapTo(['A', 'B'])),
timer(1000).pipe(mapTo(['B'])),
);
const source = deleteQueue(queueName).pipe(
tap(() => console.log('queue deleted')),
concatMap(() =>
timer(100).pipe(
concatMap(listQueues),
tap(queues => console.log('queues', queues)),
repeat(),
filter(queues => !queues.includes(queueName)),
first()
)
)
);
source.subscribe(x => console.log('next', x), e => console.error(e), () => console.log('complete'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.4/rxjs.umd.js"></script>

Should I unsubscribe after a complete?

I have a quick question about observable.
I have the following observable:
getElevation(pos: Cartographic): Observable<Cartographic> {
return new Observable(observer => {
const promise = Cesium.sampleTerrain(this.terrainProvider, 11, Cesium.Cartographic(pos.longitude, pos.latitude))
Cesium.when(promise, (updatedPositions) => {
observer.next(updatedPositions);
observer.complete();
});
});
}
In a component I have:
this.service.getElevation(value).subscribe((e) => {});
My question is, this is a one shoot observable, so I complete just after, is the complete automatically close the subscription? or, do I also have to do this:
const sub = this.service.getElevation(value).subscribe((e) => {sub.unsubscribe();});
In your case you don't need to unsubscribe.
All Observers will automatically be unsubscribed when you call complete. That said, you may want to implement your consuming (component) code do handle the possibility that the implementation of the service may change in the future.
You could do this by using the take operator which will unsubscribe after the first value is emitted:
this.service.getElevation(value).pipe(take(1)).subscribe((e) => {});
You should not unsubscribe in a subscription, it the observable emits instantly then sub is undefined.
If you want a self unsubscribing observable you can use takeUntil
finalise = new Subject();
this.service.getElevation(value).pipe(takeUntil(finalise)).subscribe((e) => {
finalise.next();
finalise.complete();
});
Brief note:
Try to control the subscription with operators such as takeUntil.
You don’t need to unsubscribe yourself if the sender(Subject) completes.
For your case, since the sender returned by getElevation function completes itself after emitting a value one time, you don’t need to either use any operator or unsubscribe yourself to unsubscribe it.
All you have to do: this.service.getElevation(value).subscribe((v) => // do what you want);

Invoke method when no observers for RxJs Subject

How to invoke a method when all the observers have unsubscribed from a subject.
Update
const alphaStore = new BehaviourSubject(0);
observer1 = alphaStore.subscribe(console.log);
observer2 = alphaStore.subscribe(console.log);
And when all of these observers unsubscribe. I want a method to be invoked. Like...
Observer1 unsubscribed
Observer2 unsubscribed
All observers left
What you describe already does the finalize() operator. Better said finalize() calls its callback when the chain disposes which means it's called when all observers unsubscribes, the chain completes or errors.
const subject = new Subject();
const shared = subject.pipe(
finalize(() => console.log('finalize')),
share(),
);
https://stackblitz.com/edit/rxjs-rebfba
When all observers unsubscribe share() unsubscribes from its source which triggers finalize().
Currently there's no way to distinguish why finalize() was invoked. See this issue https://github.com/ReactiveX/rxjs/issues/2823 and examples there on how to do it.
You can create a custom Observable, that will track the subscription count.
Heres a simple example:
let count = 0;
const tracked$ = new Observable(() => {
count++;
return ()=>{
count--;
if (count === 0) {
console.log('I am empty');
}
};
})
And then merge it with Observable that does actual work.
For simplicity sake, lets imagine its just a timer
// const tracked$ = ...
const data$ = Observable.timer(0, 5);
const result$ = data$
.merge(tracked$)
.take(5)
.subscribe(value => console.log('v:', value));
After 5 values were emitted -- it will log I am empty.
Heres a live example (with some rewrite and two subscriptions):
https://observable-playground.github.io/gist/4a7415f3528aa125fb686204041138cb
NOTE: this code uses rxjs-compat notation, which is easier to read. Above linked example uses .pipe notation, which is more common now.
Hope this helps.

observable event filters and timeout

I am very new Rxjs observable and need help with two questions.
I have this piece of code:
const resultPromise = this.service.data
.filter(response => data.Id === 'dataResponse')
.filter((response: dataResponseMessage) => response.Values.Success)
.take(1)
.timeout(timeoutInSeconds)
.map((response: dataResponseMessage) => response.Values.Token)
.toPromise();
I have following basic questions:
1- How can I change .timeout(timeoutInSeconds) to add a message so that I can debug/log later which response it fails? I looked at .timeout syntax in rxjs and didn't see an option to include any message or something.
2-I know .filter((response: dataResponseMessage) => response.Values.Success) will filter to responses with response.Values.Success but is there a syntax where I can do like this for an observable:
const resultPromise = this.service.data
.filter(response => data.Id === 'dataResponse')
.magicSyntax((response: dataResponseMessage) => {
if (response.Values.Success) {
// do something
} else {
// do something else
}
});
Thank you so much in advance and sorry if these are basic/dumb questions.
First question
If you reach timeout the operator will return you an error which can be caught with .catch operator
const resultPromise = this.service.data
.filter(response => data.Id === 'dataResponse')
.filter((response: dataResponseMessage) => response.Values.Success)
.take(1)
.timeout(timeoutInSeconds)
.catch(e=>{
//do your timeout operation here ...
return Observable.Of(e)
})
.map((response: dataResponseMessage) => response.Values.Token)
.toPromise();
Second question simply replace magicSyntax with map or mergemap depends what you want to return from this operation. it is perfectly fine to do if in side the block.
I'm assuming you are using at least Rxjs version 5.5 which introduced pipeable operators. From the docs - these can "...be accessed in rxjs/operators (notice the pluralized "operators"). These are meant to be a better approach for pulling in just the operators you need than the "patch" operators found in rxjs/add/operator/*."
If you aren't using pipeable operators, instead of passing the operators to pipe() like I did below, you can chain them using the dot notation you use in your example.
I suggest referring to learnrxjs.io for some additional info about the operators in RxJS, paired with examples.
The RxJS team has also created a BETA documentation reference.
Explanation
I assumed the first filter is receiving the response and filtering by response.Id instead of data.Id. If that wasn't a typo, you can keep the filter the same.
I added an extra line between the operators for presentation only.
mergeMap is an operator that takes a function that returns an Observable, which it will automatically subscribe to. I'm returning of() here, which creates an Observable that just emits the value provided to it.
catch was renamed to catchError in RxJS 5.5, and pipeable operators were also added, which add support for the .pipe() operator.
If you don't want to do anything besides logging the error, you can return empty(), which will immediately call complete() on the source Observable without emitting anything. EMPTY is preferred if you are using version 6.
Optional: Instead of using filter() and then take(1), you could use the first() operator, which returns a boolean, just like filter(), and unsubscribes from the source Observable after it returns true once.
import {EMPTY, of} from 'rxjs';
import {catchError, filter, take, mergeMap, timeout} from 'rxjs/operators';
const resultPromise = service.data.pipe(
// I assumed you meant response.Id, instead of data.Id
filter((response: dataResponseMessage) => response.Id === 'dataResponse'),
take(1),
// mergeMap accepts a value emitted from the source Observable, and expects an Observable to be returned, which it subscribes to
mergeMap((response: dataResponseMessage) => {
if (response.Values.Success) {
return of('Success!!');
}
return of('Not Success');
}),
timeout(timeoutInMilliseconds),
// catch was renamed to catchError in version 5.5.0
catchError((error) => {
console.log(error);
return EMPTY; // The 'complete' handler will be called. This is a static property on Observable
// return empty(); might be what you need, depending on version.
})
).toPromise();
1- you can use .do() to console.log your response.
.filter(..).do(response => console.log(response))
2- you can use .mergeMap()

rxJs publishLast not flushing out messages

I've just read http://blog.thoughtram.io/angular/2016/06/16/cold-vs-hot-observables.html and I was trying to get the publishLast working with some basic observables and I couldn't, can someone explain why?
let obs = Observable.create((observer: Observer<number>): void => {
observer.next(234);
})
.publishLast()
.refCount();
obs.subscribe((v: number) => console.log("1st subscriber: " + v));
setTimeout(() => {
obs.subscribe((v: number) => console.log("2nd subscriber: " + v));
}, 1100);
I am assuming that by "flushing out" you mean that you are not receiving any events in your subscribe block.
The problem is that publishLast can only emit when it knows the Observable will not be emitting any more values, and the only way it can do that is if you call complete on the Observer.
So your code needs to look like this:
let obs = Observable.create((observer: Observer<number>): void => {
observer.next(234);
observer.complete();
})
.publishLast()
.refCount();
#user2555964 For your use case, combining switchMap with distinctUntilChanged might provide a solution. Take a look an Angular's documentation where they use these two operators to implement a real-time search box
https://angular.io/tutorial/toh-pt6#herosearchcomponent

Resources