InstanceAsObservable<T, R> class abstract

InstanceAsObservable provide an unified way to turn an instance to an observable.

abstract class InstanceAsObservable<T, R> implements Observable<R> {
  
  const InstanceAsObservable(this.instance);

  final T instance;
}

Example - ValueNotifierAsObservable:

class ValueNotifierAsObservable<T extends ValueNotifier<R>, R> 
  extends InstanceAsObservable<T, R> {
  
  const ValueNotifierAsObservable(super.instance);
  
  @override
  Disposable observe(OnData<R> onData) {

    onData(instance.value);

    void listener() => onData(instance.value);

    instance.addListener(listener);

    return Disposable(() {
      instance.removeListener(listener);
    });
  }
}

ValueNotifierAsObservable turns a ValueNotifier<R> to an Observable<R>:

class Counter extends ValueNotifier<int> {
  Counter(): super(0);
  void increment() => value += 1;
}

void main() {
  final counter = Counter();
  final Observable<int> observable = ValueNotifierAsObservable(counter);
  final observation = observable.observe((data) {
    print('onData: $data');
  }); 
  counter.increment();
  counter.increment();
  observation.dispose();
}

Prints:

onData: 0
onData: 1
onData: 2
Implemented types
Available Extensions

Constructors

InstanceAsObservable(T instance)
Create InstanceAsObservable with instance.
const

Properties

hashCode int
The hash code for this object.
no setterinherited
instance → T
The referenced instance.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
observe(OnData<R> onData) Disposable
Use observable.observe to start observe an observable, use returned observation to stop observe.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited