UniRx SubscribeToText support for TextMeshPro

UniRx is a re-implementation of the .NET Reactive Extensions for Unity. UniRx allows you to use reactive programming , a declarative programming paradigm.

For example, using SubscribeToText method helps to subscribe an IObservable to a Unity Text component.

Example from the official documentation:

 
public Toggle MyToggle;
public InputField MyInput;
public Text MyText;
public Slider MySlider;

// On Start, you can write reactive rules for declaretive/reactive ui programming
void Start()
{
    // Toggle, Input etc as Observable (OnValueChangedAsObservable is a helper providing isOn value on subscribe)
    // SubscribeToInteractable is an Extension Method, same as .interactable = x)
    MyToggle.OnValueChangedAsObservable().SubscribeToInteractable(MyButton);

    // Input is displayed after a 1 second delay
    MyInput.OnValueChangedAsObservable()
     .Where(x => x != null)
     .Delay(TimeSpan.FromSeconds(1))
     .SubscribeToText(MyText); // SubscribeToText is helper for subscribe to text

    // Converting for human readability
    MySlider.OnValueChangedAsObservable()
     .SubscribeToText(MyText, x => Math.Round(x, 2).ToString());
}

Given the TextMeshPro integration in Unity there is a need to extend SubscribeToText to support Text Mesh Pro components.

One way to do this is to create a UnityUIExtensions.cs file inside your Unity project and add the following code:

using System;
using TMPro;

namespace UniRx.Extensions
{
    public static class UnityUIExtensions
    {
        public static IDisposable SubscribeToText(this IObservable<string> source, TextMeshProUGUI text)
        {
            return source.SubscribeWithState(text, (x, t) => t.text = x);
        }

        public static IDisposable SubscribeToText<T>(this IObservable<T> source, TextMeshProUGUI text)
        {
            return source.SubscribeWithState(text, (x, t) => t.text = x.ToString());
        }
    }
}

GitHub Gist: link