Execute method when UniRx generic Notifier data changes

using System;
using UniRx;
using UnityEngine;

namespace Test.testUniRx
{
    
    
    public class TestUniRxNotifierT : MonoBehaviour
    {
    
    
        //[ShowInInspector]
        public Notifier<Vector3> test = new Notifier<Vector3>();
        private ScheduledNotifier<Vector3> progressNotifier = new ScheduledNotifier<Vector3>();
        private IDisposable _disposable;
        private IDisposable _disposable2;
        
        //[Button]
        public void ChangeValue()
        {
    
    
            test.Value += Vector3.one;
            // progressNotifier.Report(testFloat);
        }

        //[Button]
        public void Bind()
        {
    
    
            _disposable = test.Subscribe(s =>
            {
    
    
                Debug.Log($"mylog:new T Value is : {
      
      s.ToString("f3")}");
                progressNotifier.Report(s);
            });
            _disposable2 = progressNotifier.Subscribe(x => {
    
     Debug.Log($"mylog: 输出了:{
      
      x.ToString("f3")}");}); // write www.progress
        }

        //[Button]
        public void UnBind()
        {
    
    
            _disposable.Dispose();
            _disposable2.Dispose();
        }
    }

    /// <summary>
    /// Notify T flag.
    /// </summary>
    public class Notifier<T> : IObservable<T>
    {
    
    
        readonly Subject<T> _subject = new Subject<T>();

        T _vector3Value;

        /// <summary>Current flag value</summary>
        //[ShowInInspector]
        public T Value
        {
    
    
            get => _vector3Value;
            set
            {
    
    
                _vector3Value = value;
                _subject.OnNext(value);
            }
        }

        /// <summary>
        /// Setup initial flag.
        /// </summary>
        public Notifier(T initialValue = default)
        {
    
    
            Value = initialValue;
        }

        /// <summary>
        /// Subscribe observer.
        /// </summary>
        public IDisposable Subscribe(IObserver<T> observer)
        {
    
    
            return _subject.Subscribe(observer);
        }
        
        /// <summary>
        /// Empty Action
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public IDisposable Subscribe(Action action)
        {
    
    
            return _subject.Subscribe((obj =>
            {
    
    
                action.Invoke();
            }));
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_44054505/article/details/122188403