Ingen beskrivning

RNFetchBlobReadStream.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. constructor(path:string, encoding:string, bufferSize?:?number) {
  19. if(!path)
  20. throw Error('RNFetchBlob could not open file stream with empty `path`')
  21. this.encoding = encoding || 'utf8'
  22. this.bufferSize = bufferSize
  23. this.path = path
  24. this.closed = false
  25. this._onData = () => {}
  26. this._onEnd = () => {}
  27. this._onError = () => {}
  28. this.streamId = 'RNFBRS'+ UUID()
  29. // register for file stream event
  30. let subscription = emitter.addListener(this.streamId, (e) => {
  31. let {event, detail} = e
  32. if(this._onData && event === 'data') {
  33. this._onData(detail)
  34. return
  35. }
  36. else if (this._onEnd && event === 'end') {
  37. this._onEnd(detail)
  38. }
  39. else {
  40. if(this._onError)
  41. this._onError(detail)
  42. else
  43. throw new Error(detail)
  44. }
  45. // when stream closed or error, remove event handler
  46. if (event === 'error' || event === 'end') {
  47. subscription.remove()
  48. this.closed = true
  49. }
  50. })
  51. }
  52. open() {
  53. if(!this.closed)
  54. RNFetchBlob.readStream(this.path, this.encoding, this.bufferSize || 0, this.streamId)
  55. else
  56. throw new Error('Stream closed')
  57. }
  58. onData(fn:() => void) {
  59. this._onData = fn
  60. }
  61. onError(fn) {
  62. this._onError = fn
  63. }
  64. onEnd (fn) {
  65. this._onEnd = fn
  66. }
  67. }