I need to build a offline ionic app. App api has many serve url images, about 255 datas. I used file transfer plugin to download the images, to externalApplicationStorageDirectory, and store it in sqlite database. But the images are not downloaded in accordance with the api data order. The datas are downloaded in different order and inserted differently in database.
I need to download the datas according to the api order and to be inserted like the same order to database.
// Ionic 3 with new rxjs imports
import { from } from 'rxjs/observable/from';
import { bufferCount } from 'rxjs/operators/bufferCount';
import { concatMap } from 'rxjs/operators/concatMap';
import { map } from 'rxjs/operators/map';
downloadData(): Observable<any> {
return from(this.data).pipe( // Pipe each entry of the url-array through the observable stream
bufferCount(8), // Group the entries in arrays of 8 -> 8 simultanious downloads.
map(arr => arr
.map(url => this.fileTransfer.download(url, 'target') // Download files for the 8 entries.
.catch(err => console.log(err)))), // Catch errors, so that one download failure does not stop all downloads
concatMap(arr => Promise.all(arr)) // Wait until the 8 downloads are done, then start the next package.
);
}
// With old rxjs imports
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/bufferCount';
import 'rxjs/add/operator/concatMap';
import 'rxjs/add/operator/map';
downloadData(): Observable<any> {
return Observable
.from(this.data) // Pipe each entry of the url-array through the observable stream
.bufferCount(8) // Group the entries in arrays of 8 -> 8 simultanious downloads.
.map(arr => arr
.map(url => this.fileTransfer.download(url, 'target') // Download files for the 8 entries.
.catch(err => console.log(err)))) // Catch errors, so that one download failure does not stop all downloads
.concatMap(arr => Promise.all(arr)); // Wait until the 8 downloads are done, then start the next package.
}
If you want to download one by one use this:
downloadData(): any {
return Observable
.from(this.data) // Pipe each entry of the url-array through the observable stream
.concatMap(url => this.fileTransfer.download(url, 'target') // Wait until the download is done, then start the next download.
.catch(err => console.log(err))); // Catch failures to prevent one download failure stopping all downloads.
}
I haven’t tried if it works. So if somebody finds a mistake, please tell here.