1 |
|
2 |
|
3 | import { NativeModules, NativeEventEmitter } from 'react-native';
|
4 | import { EventEmitter, EmitterSubscription } from 'fbemitter';
|
5 |
|
6 | const { CTKNativeAdManager, CTKNativeAdEmitter } = NativeModules;
|
7 |
|
8 | const nativeAdEmitter = new NativeEventEmitter(CTKNativeAdEmitter);
|
9 |
|
10 | const EVENT_DID_BECOME_VALID = 'AdsManagerDidBecomeValid';
|
11 |
|
12 | type AdManagerCachePolicy = 'none' | 'icon' | 'image' | 'all';
|
13 |
|
14 | class NativeAdsManager {
|
15 |
|
16 | placementId: string;
|
17 |
|
18 |
|
19 | adsToRequest: number;
|
20 |
|
21 |
|
22 | isValid: boolean = false;
|
23 |
|
24 |
|
25 | eventEmitter: EventEmitter = new EventEmitter();
|
26 |
|
27 | |
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 | constructor(placementId: string, adsToRequest: number = 10) {
|
34 | this.placementId = placementId;
|
35 | this.adsToRequest = adsToRequest;
|
36 |
|
37 | this._listenForStateChanges();
|
38 |
|
39 | CTKNativeAdManager.init(placementId, adsToRequest);
|
40 | }
|
41 |
|
42 | |
43 |
|
44 |
|
45 |
|
46 | _listenForStateChanges() {
|
47 | nativeAdEmitter.addListener(
|
48 | 'CTKNativeAdsManagersChanged',
|
49 | managers => {
|
50 | const isValidNew = managers[this.placementId];
|
51 | const isValid = this.isValid;
|
52 |
|
53 | if (isValid !== isValidNew && isValidNew) {
|
54 | this.isValid = true;
|
55 | this.eventEmitter.emit(EVENT_DID_BECOME_VALID);
|
56 | }
|
57 | },
|
58 | );
|
59 | }
|
60 |
|
61 | |
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | onAdsLoaded(func: Function): EmitterSubscription {
|
68 | if (this.isValid) {
|
69 | setTimeout(func);
|
70 | return {
|
71 | remove: () => {},
|
72 | };
|
73 | }
|
74 |
|
75 | return this.eventEmitter.once(EVENT_DID_BECOME_VALID, func);
|
76 | }
|
77 |
|
78 | |
79 |
|
80 |
|
81 | disableAutoRefresh() {
|
82 | CTKNativeAdManager.disableAutoRefresh(this.placementId);
|
83 | }
|
84 |
|
85 | |
86 |
|
87 |
|
88 |
|
89 |
|
90 | setMediaCachePolicy(cachePolicy: AdManagerCachePolicy) {
|
91 | CTKNativeAdManager.setMediaCachePolicy(this.placementId, cachePolicy);
|
92 | }
|
93 |
|
94 | toJSON() {
|
95 | return this.placementId;
|
96 | }
|
97 | }
|
98 |
|
99 | export default NativeAdsManager;
|