Поделиться через


Метод Observable.Amb TSource> (IObservable<TSource>, IObservable<TSource>)<

Распространяет наблюдаемую последовательность, которая реагирует первой с указанной первой и второй последовательностью.

Пространство имен:System.Reactive.Linq
Сборки: System.Reactive (в System.Reactive.dll)

Синтаксис

'Declaration
<ExtensionAttribute> _
Public Shared Function Amb(Of TSource) ( _
    first As IObservable(Of TSource), _
    second As IObservable(Of TSource) _
) As IObservable(Of TSource)
'Usage
Dim first As IObservable(Of TSource)
Dim second As IObservable(Of TSource)
Dim returnValue As IObservable(Of TSource)

returnValue = first.Amb(second)
public static IObservable<TSource> Amb<TSource>(
    this IObservable<TSource> first,
    IObservable<TSource> second
)
[ExtensionAttribute]
public:
generic<typename TSource>
static IObservable<TSource>^ Amb(
    IObservable<TSource>^ first, 
    IObservable<TSource>^ second
)
static member Amb : 
        first:IObservable<'TSource> * 
        second:IObservable<'TSource> -> IObservable<'TSource> 
JScript does not support generic types and methods.

Параметры типа

  • TSource
    Тип источника.

Параметры

  • first
    Тип: System.IObservable<TSource>
    Первая наблюдаемая последовательность.
  • second
    Тип: System.IObservable<TSource>
    Вторая наблюдаемая последовательность.

Возвращаемое значение

Тип: System.IObservable<TSource>
Наблюдаемая последовательность, которая первой ответила из набора заданных последовательностей.

Примечание об использовании

В Visual Basic и C# этот метод можно вызвать как метод экземпляра для любого объекта типа IObservable<TSource>. При вызове метода для экземпляра следует опускать первый параметр. Дополнительные сведения см. в разделе или .

Комментарии

Имя оператора Amb сокращено от "неоднозначно". Оператор Amb принимает две или более последовательностей и возвращает первую последовательность для ответа. Оператор Amb использует параллельную обработку, чтобы определить, какая последовательность возвращает первый элемент.

Amb можно вызвать как метод расширения, как показано в примере кода в этом разделе, или как статический метод. На основе примера кода, приведенного в этом разделе, в следующем фрагменте кода показано, как вызвать статический метод Amb.

      int[] sequence1 = { 1, 2, 3 };
      int[] sequence2 = { 4, 5, 6 };
      int[] sequence3 = { 7, 8, 9 };

      //*** The first item in the sequence1 event stream is delayed by 3 seconds. ***//
      IObservable<int> firstSource = sequence1.ToObservable().Delay(TimeSpan.FromSeconds(3));

      //*** The first event in the sequence2 event stream is only delayed by 2 seconds. ***//
      IObservable<int> secondSource = sequence2.ToObservable().Delay(TimeSpan.FromSeconds(2));

      //*** The first event in the sequence3 event stream is only delayed by 1 second.  ***//
      IObservable<int> thirdSource = sequence3.ToObservable().Delay(TimeSpan.FromSeconds(1));


      //*****************************************************************************************//
      //***                                                                                   ***//
      //*** The Amb operator will simply return the observable sequence which responds first. ***//
      //*** The other sequence will be ignored.                                               ***//
      //***                                                                                   ***//
      //*** In this example "thirdSource", which contains sequence3, will respond before      ***//
      //*** "firstSource" and "secondSource". So "thirdSource" will be the observable         ***//
      //*** sequence returned from the Amb operator. It will be subscribed to and written     ***//
      //*** to the console.                                                                   ***//
      //***                                                                                   ***//
      //*****************************************************************************************//


      //*** The static method allows the Amb operator to process more than two sequences ***//
      using (IDisposable handle = Observable.Amb(firstSource, secondSource, thirdSource).Subscribe(value => Console.WriteLine(value)))
      {
        Console.WriteLine("\nPress ENTER to exit...\n");
        Console.ReadLine();
      }

Amb также можно вызвать в качестве метода расширения для более чем двух последовательностей. Чтобы использовать этот подход, создайте последовательность последовательностей. Это демонстрируется в следующем фрагменте кода.

      int[] sequence1 = { 1, 2, 3 };
      int[] sequence2 = { 4, 5, 6 };
      int[] sequence3 = { 7, 8, 9 };

      //*** The first item in the sequence1 event stream is delayed by 3 seconds. ***//
      IObservable<int> firstSource = sequence1.ToObservable().Delay(TimeSpan.FromSeconds(3));

      //*** The first event in the sequence2 event stream is only delayed by 2 seconds. ***//
      IObservable<int> secondSource = sequence2.ToObservable().Delay(TimeSpan.FromSeconds(2));

      //*** The first event in the sequence3 event stream is only delayed by 1 second.  ***//
      IObservable<int> thirdSource = sequence3.ToObservable().Delay(TimeSpan.FromSeconds(1));


      //*****************************************************************************************//
      //***                                                                                   ***//
      //*** The Amb operator will simply return the observable sequence which responds first. ***//
      //*** The other sequence will be ignored.                                               ***//
      //***                                                                                   ***//
      //*** In this example "thirdSource", which contains sequence3, will respond before      ***//
      //*** "firstSource" and "secondSource". So "thirdSource" will be the observable         ***//
      //*** sequence returned from the Amb operator. It will be subscribed to and written     ***//
      //*** to the console.                                                                   ***//
      //***                                                                                   ***//
      //*****************************************************************************************//


      //*** Call the extension method on a sequence of any number of sequences. ***//
      IObservable<int>[] sources = new[] { firstSource, secondSource, thirdSource };
      using(IDisposable handle = sources.Amb().Subscribe(value => Console.WriteLine(value)))
      {
        Console.WriteLine("\nPress ENTER to exit...\n");
        Console.ReadLine();
      }

Примеры

В следующем примере демонстрируется оператор Amb путем его применения с двумя последовательностями целых чисел. Доставка целых чисел в первой последовательности откладывается на три секунды. Доставка целых чисел во второй последовательности откладывается только на две секунды. Поэтому вторая последовательность отвечает первой и является результатом оператора Amb, как показано ниже.

using System;
using System.Reactive.Linq;

namespace Example
{

  class Program
  {

    static void Main()
    {
      int[] sequence1 = { 1, 2, 3 };
      int[] sequence2 = { 4, 5, 6 };

      //*** The first event in observable sequence1 is delayed by 3 seconds. ***//
      IObservable<int> firstSource = sequence1.ToObservable().Delay(TimeSpan.FromSeconds(3));

      //*** The first event in observable sequence2 is only delayed by 2 seconds. ***//
      IObservable<int> secondSource = sequence2.ToObservable().Delay(TimeSpan.FromSeconds(2));


      //*****************************************************************************************//
      //***                                                                                   ***//
      //*** The Amb operator will simply return the observable sequence which responds first. ***//
      //*** The other sequence will be ignored.                                               ***//
      //***                                                                                   ***//
      //*** In this example "secondSource", which contains sequence2, will respond before     ***//
      //*** "firstSource". So "secondSource" will be the observable sequence returned from    ***//
      //*** the Amb operator.                                                                 ***//
      //***                                                                                   ***//
      //*****************************************************************************************//

      using (IDisposable handle = firstSource.Amb(secondSource).Subscribe(value => Console.WriteLine(value)))
      {
        Console.WriteLine("Press Enter to exit...\n");
        Console.ReadLine();
      }
    }
  }
}

Выходные данные примера кода выводятся следующим образом.

Press Enter to exit...

4
5
6

См. также:

Ссылка

Наблюдаемый класс

Перегрузка Amb

Пространство имен System.Reactive.Linq