Add push$ to Collection; make Container listen for retroactive blueprint changes
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import {AsyncPipe, Pipeline} from '../support/Pipe'
|
||||
import {Unsubscribe, Subscription} from '../support/BehaviorSubject'
|
||||
|
||||
type CollectionItem<T> = T
|
||||
type MaybeCollectionItem<T> = CollectionItem<T> | undefined
|
||||
@@ -50,6 +51,8 @@ export {
|
||||
class Collection<T> {
|
||||
private storedItems: CollectionItem<T>[] = []
|
||||
|
||||
private pushSubscribers: Subscription<T>[] = []
|
||||
|
||||
/**
|
||||
* Create a new collection from an array of items.
|
||||
* @param items
|
||||
@@ -966,6 +969,7 @@ class Collection<T> {
|
||||
*/
|
||||
prepend(item: CollectionItem<T>): Collection<T> {
|
||||
this.storedItems = [item, ...this.storedItems]
|
||||
this.callPushSubscribers(item)
|
||||
return this
|
||||
}
|
||||
|
||||
@@ -975,9 +979,33 @@ class Collection<T> {
|
||||
*/
|
||||
push(item: CollectionItem<T>): Collection<T> {
|
||||
this.storedItems.push(item)
|
||||
this.callPushSubscribers(item)
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to listen for items being added to the collection.
|
||||
* @param sub
|
||||
*/
|
||||
push$(sub: Subscription<T>): Unsubscribe {
|
||||
this.pushSubscribers.push(sub)
|
||||
return {
|
||||
unsubscribe: () => this.pushSubscribers = this.pushSubscribers.filter(x => x !== sub),
|
||||
}
|
||||
}
|
||||
|
||||
/** Helper to notify subscribers that an item has been pushed to the collection. */
|
||||
private callPushSubscribers(item: T): void {
|
||||
this.pushSubscribers
|
||||
.forEach(sub => {
|
||||
if ( typeof sub === 'object' ) {
|
||||
sub?.next?.(item)
|
||||
} else {
|
||||
sub(item)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Push the given items to the end of this collection.
|
||||
* Unlike `merge()`, this mutates the current collection's items.
|
||||
@@ -987,6 +1015,7 @@ class Collection<T> {
|
||||
const concats = items instanceof Collection ? items.all() : items
|
||||
for ( const item of concats ) {
|
||||
this.storedItems.push(item)
|
||||
this.callPushSubscribers(item)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user