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