Cysharp / R3

The new future of dotnet/reactive and UniRx.
MIT License
1.71k stars 70 forks source link

Add Godot-signal-as-observable mapper #199

Open lfod1997 opened 2 months ago

lfod1997 commented 2 months ago

Summary

Extension methods and utility classes for easy conversion from a Godot signal to an observable.

Motivation

Although we can use FromEvent to create observable from any event:

var observable = Observable.FromEvent<WhoType>(
    h => myCheese.Touched += h,
    h => myCheese.Touched -= h
);

It:

  1. usually involves two capturing lambdas as there's no "FromEventWithState<T, TState>"; otherwise 2 methods must be introduced just for this
  2. requires a Func<Action<T>, TDelegate> conversion (= more boilerplate!) if the signal has more than one event arg
  3. is verbose
  4. does multiple connecting if multiple subscribers
  5. will not call OnComplete unless canceled by a CancellationToken

Prefer something easier:

var observable = myCheese.SignalAsObservable<WhoType>(Cheese.SignalName.Touched, completeOnExitTree: true);
  1. no capturing
  2. no converters when multi-arg
  3. DRY syntax
  4. connects once, to a backing Subject's OnNext
  5. gives the option (true by default) to call OnComplete automatically, if the GodotObject is a Node and has exited tree
  6. refers to Godot's SignalName explicitly