Reactive approach to simple imperative task

后端 未结 3 1329
予麋鹿
予麋鹿 2021-01-05 07:54

Application requirements:

  • subscribe to two event streams A and B
  • for each A event there should be corresponding B event some time later
  • the a
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-05 08:08

    I think this does what you want, albeit it is C# rather than Java - I'm sure you can convert easily enough.

    private IObservable MonitorAB(
        IObservable a, IObservable b, TimeSpan threshold)
    {
        return Observable.Create(o =>
            b.Publish(pb =>
                a.Select(ax =>
                    pb.Where(pbx => pbx == ax)
                        .Take(1)
                        .Timeout(threshold, Observable.Return(-1L))
                        .Select(pbx => String.Format("{0},{1}", ax, pbx)))
                .Merge())
                .Subscribe(o));
    }
    

    So this simply uses the inline .Publish to make sure b is hot within the query. The outer .Select filters the published pb observable for those that match the value from a (matching a & b), takes only one cause we only want one, and then does a .Timeout for the threshold time and returns a -1L (long) if the timeout is reached. The inner .Select just turns the two long values into a single string. At this point the query is an IObservable> so the .Merge flattens it out.

提交回复
热议问题