Aucune description

RNFetchBlobReadStream.js 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2016 wkh237@github. All rights reserved.
  2. // Use of this source code is governed by a MIT-style license that can be
  3. // found in the LICENSE file.
  4. // @flow
  5. import {
  6. NativeModules,
  7. DeviceEventEmitter,
  8. NativeAppEventEmitter,
  9. } from 'react-native'
  10. import UUID from '../utils/uuid'
  11. const RNFetchBlob = NativeModules.RNFetchBlob
  12. const emitter = DeviceEventEmitter
  13. export default class RNFetchBlobReadStream {
  14. path : string;
  15. encoding : 'utf8' | 'ascii' | 'base64';
  16. bufferSize : ?number;
  17. closed : boolean;
  18. tick : number = 10;
  19. constructor(path:string, encoding:string, bufferSize?:?number, tick:number) {
  20. if(!path)
  21. throw Error('RNFetchBlob could not open file stream with empty `path`')
  22. this.encoding = encoding || 'utf8'
  23. this.bufferSize = bufferSize
  24. this.path = path
  25. this.closed = false
  26. this.tick = tick
  27. this._onData = () => {}
  28. this._onEnd = () => {}
  29. this._onError = () => {}
  30. this.streamId = 'RNFBRS'+ UUID()
  31. // register for file stream event
  32. let subscription = emitter.addListener(this.streamId, (e) => {
  33. let {event, detail} = e
  34. if(this._onData && event === 'data') {
  35. this._onData(detail)
  36. return
  37. }
  38. else if (this._onEnd && event === 'end') {
  39. this._onEnd(detail)
  40. }
  41. else {
  42. if(this._onError)
  43. this._onError(detail)
  44. else
  45. throw new Error(detail)
  46. }
  47. // when stream closed or error, remove event handler
  48. if (event === 'error' || event === 'end') {
  49. subscription.remove()
  50. this.closed = true
  51. }
  52. })
  53. }
  54. open() {
  55. if(!this.closed)
  56. RNFetchBlob.readStream(this.path, this.encoding, this.bufferSize || 10240 , this.tick || -1, this.streamId)
  57. else
  58. throw new Error('Stream closed')
  59. }
  60. onData(fn:() => void) {
  61. this._onData = fn
  62. }
  63. onError(fn) {
  64. this._onError = fn
  65. }
  66. onEnd (fn) {
  67. this._onEnd = fn
  68. }
  69. }