UNPKG

2.71 kBJavaScriptView Raw
1/* @flow */
2
3import { NativeModules, NativeEventEmitter } from 'react-native';
4import { EventEmitter, EmitterSubscription } from 'fbemitter';
5
6const { CTKNativeAdManager, CTKNativeAdEmitter } = NativeModules;
7
8const nativeAdEmitter = new NativeEventEmitter(CTKNativeAdEmitter);
9
10const EVENT_DID_BECOME_VALID = 'AdsManagerDidBecomeValid';
11
12type AdManagerCachePolicy = 'none' | 'icon' | 'image' | 'all';
13
14class NativeAdsManager {
15 /** {@string} with placement id of ads **/
16 placementId: string;
17
18 /** {@number} of ads to request at once **/
19 adsToRequest: number;
20
21 /** {@boolean} indicating whether AdsManager is ready to serve ads **/
22 isValid: boolean = false;
23
24 /** {@EventEmitter} used for sending out updates **/
25 eventEmitter: EventEmitter = new EventEmitter();
26
27 /**
28 * Creates an instance of AdsManager with a given placementId and adsToRequest.
29 * Default number of ads to request is `10`.
30 *
31 * AdsManager will become loading ads immediately
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 * Listens for AdManager state changes and updates internal state. When it changes,
44 * callers will be notified of a change
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 * Used to listening for state changes
63 *
64 * If manager already became valid, it will call the function w/o registering
65 * handler for events
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 * Disables auto refreshing for this native ad manager
80 */
81 disableAutoRefresh() {
82 CTKNativeAdManager.disableAutoRefresh(this.placementId);
83 }
84
85 /**
86 * Set the native ads manager caching policy. This controls which media from
87 * the native ads are cached before the onAdsLoaded is called.
88 * The default is to not block on caching.
89 */
90 setMediaCachePolicy(cachePolicy: AdManagerCachePolicy) {
91 CTKNativeAdManager.setMediaCachePolicy(this.placementId, cachePolicy);
92 }
93
94 toJSON() {
95 return this.placementId;
96 }
97}
98
99export default NativeAdsManager;