有状态生命周期可观察到

时间:2019-03-02 02:34:53

标签: dart observable reactivex

一般的设计问题可以描述为:

我有一个Websocket连接,它具有严格的生命周期值得尊重-它希望正确调用connectdisconnect,并且因为它与系统对话,所以使用。在此websocket连接中,我们有多个不同的Subscription对象,每个对象都有一个严格的生命周期,需要遵守该生命周期(subscribeunsubscribe),并且这些操作取决于其父Websocket的状态取得成功。

这是三个嵌套生命周期可观察对象的理想行为的时间表,其中C依赖于B,而B依赖于A:


A = someInput.switchMap((i) => LifecycleObservable())
B = A.switchMap((a) => LifecycleObservable())
C = B.switchMap((b) => LifecycleObservable())

C.listen(print);

// <-- listen to c
// <-- produce [someInput]
setup A
setup B
setup C
// <-- c is produced

// <-- c is unsubscribed
teardown C
teardown B
teardown A

// <-- C is re-subscribed-to
setup A
setup B
setup C

// <-- produce [someInput]
teardown C
teardown B
teardown A
setup A
setup B
setup C
// <-- c is produced

第一个问题:这是反模式吗?我在网络上找不到很多关于这种模式的信息,但是似乎可观察到的东西很标准:有些对象只有生命周期,有些对象可能要依赖它。

我可以使用以下方法接近理想的行为:

class LifecycleObservable {
  static Observable<T> fromObservable<T>({
    @required Observable<T> input,
    @required Future<void> Function(T) setup,
    @required Future<void> Function(T) teardown,
  }) {
    return input.asyncMap((T _input) async {
      await setup(_input);
      return _input;
    }).switchMap((T _input) {
      return Observable<T>(Observable.never()) //
          .startWith(_input)
          .doOnCancel(() async {
        await teardown(_input);
      });
    });
  }
}

此代码接受状态对象流,在它们产生时在它们上运行setup,并在teardown中取消可观察到的状态时在它们上运行switchMap

在原始理想化的时间轴中生成第二个[someInput]时会发生问题:使用上面的代码,我得到一个像这样的调用图

// <-- listen to c
// <-- produce [someInput]
setup A
setup B
setup C
// <-- c is produced

// <-- produce [someInput]
teardown A
setup A
teardown B
setup B
teardown C
setup C
// <-- c is produced

问题在于,如果B依赖于A(例如从依赖于开放websocket传输的订阅中调用unsubscribe),则此拆卸顺序将破坏每个对象的预期生命周期(订阅尝试发送{{ 1}}在封闭的网络套接字传输中。

1 个答案:

答案 0 :(得分:0)

在我看来,可观察的模式无法表达这些语义。具体来说,可观察模式不是为级联依赖性而设计的—父可观察者对其子可观察对象的状态一无所知。

我用以下的dart代码为自己解决了这个问题。我敢肯定这很糟糕,但它似乎通常对我有用。


class WithLifecycle<T> {
  final FutureOr<void> Function() setup;
  final FutureOr<void> Function() teardown;
  final T value;
  final WithLifecycle parent;

  List<WithLifecycle> _children = [];
  bool _disposed = false;
  WithLifecycle({
    @required this.value,
    this.setup,
    this.teardown,
    this.parent,
  });

  void addDependency(WithLifecycle child) => _children.add(child);
  void removeDependency(WithLifecycle child) => _children.remove(child);
  Future<void> init() async {
    parent?.addDependency(this);
    await setup();
  }

  Future<void> dispose() async {
    if (_disposed) {
      return;
    }

    _disposed = true;
    for (var _child in _children) {
      await _child.dispose();
    }
    _children.clear();
    await teardown();
  }
}

然后在使用可观察对象时用于创建必要的依赖关系链:

class LifecycleObservable {
  static Observable<WithLifecycle<T>> fromObservable<T>({
    @required Observable<T> value,
    WithLifecycle parent,
    @required Future<void> Function(T) setup,
    @required Future<void> Function(T) teardown,
  }) {
    return value.concatMap((T _value) {
      final withLifecycle = WithLifecycle<T>(
        value: _value,
        parent: parent,
        setup: () => setup(_value),
        teardown: () => teardown(_value),
      );
      return Observable<WithLifecycle<T>>(Observable.never())
          .startWith(withLifecycle)
          .doOnListen(() async {
        await withLifecycle.init();
      }).doOnCancel(() async {
        await withLifecycle.dispose();
      });
    });
  }
}

用法类似于

token$ = PublishSubject();
    channel$ = token$.switchMap((token) {
      return LifecycleObservable.fromObservable<IOWebSocketChannel>(
          value: Observable.just(IOWebSocketChannel.connect(Constants.connectionString)),
          setup: (channel) async {
            print("setup A ${channel.hashCode}");
          },
          teardown: (channel) async {
            print("teardown A ${channel.hashCode}");
            await channel.sink.close(status.goingAway);
          });
    });

    streams$ = channel$.switchMap((channel) {
      return LifecycleObservable.fromObservable<Stream<String>>(
        parent: channel,
        value: Observable.just(channel.value.stream.cast<String>()),
        setup: (thing) async {
          print("setup B ${thing.hashCode}");
        },
        teardown: (thing) async {
          print("teardown B ${thing.hashCode}");
        },
      );
    });

    messages = streams$.flatMap((i) => i.value).share();

并最终得到如下调用图

// <- push [token]
flutter: setup A 253354366
flutter: setup B 422603720
// <- push [token]
flutter: teardown B 422603720
flutter: teardown A 253354366
flutter: setup A 260164938
flutter: setup B 161253018