1

Preconditions: The ref.getDownload() returns an Observable which only can be subscribed, if the task.snapshotChanges()-Observable completed.

This code-snippet works:

task.snapshotChanges().subscribe({
  complete: () => {
    ref.getDownloadURL().subscribe((downloadUrl) => console.log(downloadUrl));
  }
});

This code-snippet does NOT work:

concat(
  task.snapshotChanges(),
  ref.getDownloadURL()
).pipe(
  last()
).subscribe((downloadUrl) => console.log(downloadUrl));

getDownloadUrl throws an error (404 file not found), because it seems ref.getDownloadUrl is subscribed to early.

Why subscribes the ref.getDownloaded()-Observable and does not wait until task.snapshotChanges() completes? The concat-operator should ensure this behaviour. Or am I wrong?

Catweazle
  • 105
  • 1
  • 8

1 Answers1

1

The function ref.getDownloadURL() is called when the concat(..) Observable is created. See:

const { of, concat } = rxjs; 
const { delay } = rxjs.operators;

const fetch1 = () => { console.log('run fetch1'); return of('from 1').pipe(delay(2000)) }
const fetch2 = () => { console.log('run fetch2'); return of('from 2').pipe(delay(2000)) }

concat(fetch1(), fetch2()).subscribe(console.log);
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

ref.getDownloadURL() seems to query the database directly when it gets called and not when the Observable it returns gets subscribed to.

You can wrap ref.getDownloadURL() with defer to only execute it when the Observable is subscribed to.

const { of, concat, defer } = rxjs; 
const { delay } = rxjs.operators;

const fetch1 = () => { console.log('run fetch1'); return of('from 1').pipe(delay(2000)) }
const fetch2 = () => { console.log('run fetch2'); return of('from 2').pipe(delay(2000)) }

concat(fetch1(), defer(() => fetch2())).subscribe(console.log);
<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

Also see my answer here https://stackoverflow.com/a/57671521/9423231

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
frido
  • 13,065
  • 5
  • 42
  • 56