Combining Observables when both change simultaneously

℡╲_俬逩灬. 提交于 2019-12-06 17:25:46

I have found one possible answer, but it is not the best and I would like others.

I discovered the pausable combinator. By passing in a stream that emits True or False, you can control if a sequence will be paused. Here is a modification of my example:

import rx

stream1 = rx.subjects.BehaviorSubject(1)
stream2 = rx.subjects.BehaviorSubject(2)

pauser = rx.subjects.BehaviorSubject(True)
rx.Observable\
         .combine_latest(stream1, stream2, lambda x, y: (x, y))\
         .pausable(pauser)\
         .subscribe(print)

# Begin updating simultaneously
pauser.on_next(False)
stream1.on_next(3)
stream2.on_next(4)

# Update done, resume combined stream
pauser.on_next(True)

# Prints:
# (1, 2)
# (3, 4)

To apply to my GUI, I can create a BehaviorSubject called updating in my model that emits whether or not the whole model is being updated. For example, if stream1 and stream2 are being simultaneously updated, then I can set updating to True. On any visualizations that are expensive to produce, I can apply the value of updating to pause the combined stream.

This works in Rx for c#:

var throttled = source.Publish(hot => hot.Buffer(() => hot.Throttle(dueTime));

The dueTime value here is a TimeSpan in .NET. It merely says what the window of time is that you want to have inactivity before a value it produced. This basically gobbles up values produced "simultaneously" within a margin of time.

The source in this case would be your .combine_latest(...) observable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!