Skip to content

Sanitize callback threads

While some of the callbacks may execute on the Unity main thread, we cannot guarantee which thread each callback may be triggered on. As such, before interacting with UI objects, make sure you are using the correct thread. For more information about this, check Unity's official documentation about multithreading Unity - What is Multithreading? .

Warning

Remember that Unity pauses the main thread when showing a fullscreen ad. You should not use the main thread for some callbacks, like the OnImpression one, as you usually want to track the event as soon as it happens, and not when the ad closes and Unity resumes the main thread.

There are multiple alternatives for sanitizing callbacks:

  • Using the XMediatorMainThreadDispatcher class that we provide with XMediator SDK.

    Example using XMediatorMainThreadDispatcher

    XMediatorAds.Rewarded.OnEarnedReward += _ => {
        XMediatorMainThreadDispatcher.Enqueue(() => 
            Debug.Log("This is executed from the main thread")
        );
    };
    
  • If you are using UniRx extensions, chaining the MainThreadDispatcher to your observables with the .ObserveOnMainThread() operator.

    Example using neuecc/UniRx ObserveOnMainThread() operator

    var subject = new Subject<Unit>();
    
    subject.ObserveOnMainThread().Subscribe(_ => {
        Debug.Log("This is executed from the main thread")
    });
    
    XMediatorAds.Rewarded.OnEarnedReward += _ => {
        subject.OnNext(Unit.Default);
    };
    
  • Setting flags in your MonoBehaviour scripts and reacting to them accordingly on the Update() method, since it's guaranteed to run on the MainThread.

    Example using MonoBehaviour's Update() method

    private bool _shouldRewardUser;
    
    void Start()
    {
        // [...]
        XMediatorAds.Rewarded.OnEarnedReward += () => _shouldRewardUser = true;
    }
    
    void Update()
    {
        if (_shouldRewardUser)
        {
            _shouldRewardUser = false;
            Debug.Log("This is executed from the main thread");
        }
    }