1 | import { NativeModules, NativeEventEmitter, DeviceEventEmitter, Platform } from 'react-native'
|
2 |
|
3 | const { RNBranch, RNBranchEventEmitter } = NativeModules
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | export default class BranchSubscriber {
|
9 | |
10 |
|
11 |
|
12 | _nativeEventEmitter = Platform.select({
|
13 | android: DeviceEventEmitter,
|
14 | ios: new NativeEventEmitter(RNBranchEventEmitter),
|
15 | })
|
16 |
|
17 | |
18 |
|
19 |
|
20 |
|
21 |
|
22 | _checkCachedEvents = true
|
23 |
|
24 | |
25 |
|
26 |
|
27 | _subscribed = false
|
28 |
|
29 | |
30 |
|
31 |
|
32 |
|
33 | options = {}
|
34 |
|
35 | |
36 |
|
37 |
|
38 |
|
39 |
|
40 | constructor(options) {
|
41 | this.options = options || {}
|
42 | if ('checkCachedEvents' in this.options) {
|
43 | this._checkCachedEvents = this.options.checkCachedEvents
|
44 | }
|
45 |
|
46 | this.initSessionStart = null
|
47 | this.initSessionSuccess = null
|
48 | this.initSessionError = null
|
49 | }
|
50 |
|
51 | subscribe() {
|
52 | if (this._subscribed) return
|
53 |
|
54 | this._subscribed = true
|
55 |
|
56 | if (this._checkCachedEvents) {
|
57 | |
58 |
|
59 |
|
60 |
|
61 | this._checkCachedEvents = false
|
62 | RNBranch.redeemInitSessionResult().then((result) => {
|
63 | if (result) {
|
64 |
|
65 | if('params' in result && !!result['params']) {
|
66 | result['params']['+rn_cached_initial_event'] = true
|
67 | }
|
68 |
|
69 | |
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | if (this.options.onOpenStart && 'uri' in result) {
|
80 | this.options.onOpenStart({uri: result.uri, cachedInitialEvent: true})
|
81 | }
|
82 | if (this.options.onOpenComplete) {
|
83 |
|
84 | this.options.onOpenComplete(result)
|
85 | }
|
86 | }
|
87 |
|
88 | this._subscribe()
|
89 | })
|
90 | }
|
91 | else {
|
92 | this._subscribe()
|
93 | }
|
94 | }
|
95 |
|
96 | |
97 |
|
98 |
|
99 |
|
100 |
|
101 | _subscribe() {
|
102 | if (this.options.onOpenStart) {
|
103 | this.initSessionStart = this._nativeEventEmitter.addListener(RNBranch.INIT_SESSION_START, this.options.onOpenStart)
|
104 | }
|
105 |
|
106 | if (this.options.onOpenComplete) {
|
107 | this.initSessionSuccess = this._nativeEventEmitter.addListener(RNBranch.INIT_SESSION_SUCCESS, this.options.onOpenComplete)
|
108 | this.initSessionError = this._nativeEventEmitter.addListener(RNBranch.INIT_SESSION_ERROR, this.options.onOpenComplete)
|
109 | }
|
110 | }
|
111 |
|
112 | |
113 |
|
114 |
|
115 | unsubscribe() {
|
116 | if (!this._subscribed) return
|
117 |
|
118 | this._subscribed = false
|
119 |
|
120 | if (this.options.onOpenStart) {
|
121 | if (this.initSessionStart) {
|
122 | this.initSessionStart.remove()
|
123 | };
|
124 | }
|
125 |
|
126 | if (this.options.onOpenComplete) {
|
127 | if (this.initSessionSuccess) {
|
128 | this.initSessionSuccess.remove();
|
129 | }
|
130 | if (this.initSessionError) {
|
131 | this.initSessionError.remove()
|
132 | }
|
133 | }
|
134 | }
|
135 | }
|