Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch.
I would greatly appreciate it if someone could help me understand why the code snippet below produces the output shown:
export function cursor$ <T> (cursor: Cursor<T>): Observable<T> {
let counter = 1
const d$ = (): Observable<T> => {
counter++
return from(cursor.hasNext())
.pipe(
tap(() => console.log(counter, 'before')),
concatMap(x => x ? from( <Promise<T>>cursor.next() ) : empty()),
tap(() => console.log(counter, 'between')),
expand(() => d$()),
tap(() => console.log(counter, 'after'))
)
}
return d$()
}
As each item gets logged in the subscribe, 'done' is printed upon completion.
2 'before'
2 'between'
2 'after'
{ _id: 5bb5d47bbfa2d3ea077c37a6, name: 'Jeff' }
3 'before'
3 'between'
3 'after'
3 'after'
{ _id: 5bb5d483bfa2d3ea077c37a8, name: 'Jerald' }
5 'before'
5 'before'
5 'between'
5 'after'
5 'after'
{ _id: 5bb5d493bfa2d3ea077c37aa, name: 'Somebody' }
7 'between'
7 'after'
7 'after'
7 'after'
{ _id: 5bb5df8dbfa2d3ea077c39c8, name: 'Waddup' }
10 'before'
10 'before'
10 'before'
10 'before'
10 'before'
done