Compartilhar via


Método Observable.Create TSource> (Func<IObserver<TSource>, IDisposable>)<

Cria uma sequência observável com base em uma implementação de método de assinatura.

Namespace:System.Reactive.Linq
Assembly: System.Reactive (em System.Reactive.dll)

Sintaxe

'Declaration
Public Shared Function Create(Of TSource) ( _
    subscribe As Func(Of IObserver(Of TSource), IDisposable) _
) As IObservable(Of TSource)
'Usage
Dim subscribe As Func(Of IObserver(Of TSource), IDisposable)
Dim returnValue As IObservable(Of TSource)

returnValue = Observable.Create(subscribe)
public static IObservable<TSource> Create<TSource>(
    Func<IObserver<TSource>, IDisposable> subscribe
)
public:
generic<typename TSource>
static IObservable<TSource>^ Create(
    Func<IObserver<TSource>^, IDisposable^>^ subscribe
)
static member Create : 
        subscribe:Func<IObserver<'TSource>, IDisposable> -> IObservable<'TSource> 
JScript does not support generic types and methods.

Parâmetros de tipo

  • TSource
    O tipo de fonte.

Parâmetros

Valor Retornado

Tipo: System.IObservable<TSource>
A sequência observável com a implementação especificada para o método subscribe.

Comentários

O operador Create permite que você crie suas próprias sequências personalizadas sem implementar totalmente a interface IObservable<T> para sua sequência. Usando esse operador, você apenas implementa uma função de assinatura que usa um IObserver<T> em que T é seu tipo e retorna a interface IDisposable usada para cancelar a assinatura chamando IDisposable::D ispose(). O uso desse operador é preferencial em relação à implementação manual da interface T> IObservable<.

Exemplos

Este exemplo simula um sistema hipotético de tíquetes em que uma sequência observável de tíquetes é fornecida sem implementar totalmente o Tíquete> IObservable<. A classe TicketFactory implementa seu próprio método de assinatura chamado TicketSubscribe. Esse método é passado como o parâmetro de assinatura para o operador Create. TicketSubscribe cria uma sequência contínua de tíquetes em outro thread até que a assinatura seja cancelada chamando o método Dispose na interface IDisposable retornada de TicketSubscribe. Um Tíquete> IObserver<é passado para TicketSubscribe. Cada tíquete na sequência é entregue chamando o Tíquete> IObserver<. OnNext(). A ação de observador executada para a assinatura exibe cada tíquete para a janela do console.

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Reactive.Linq;

namespace Example
{

  class Program
  {

    static void Main()
    {
      IObservable<Ticket> ticketObservable = Observable.Create((Func<IObserver<Ticket>, IDisposable>)TicketFactory.TicketSubscribe);

      //*********************************************************************************//
      //*** This is a sequence of tickets. Display each ticket in the console window. ***//
      //*********************************************************************************//
      using(IDisposable handle = ticketObservable.Subscribe(ticket => Console.WriteLine(ticket.ToString())))
      {
        Console.WriteLine("\nPress ENTER to unsubscribe...\n");
        Console.ReadLine();
      }
    }
  }


  //***************************************************************************************************//
  //***                                                                                             ***//
  //*** The Ticket class just represents a hypothetical ticket composed of an ID and a timestamp.   ***//
  //***                                                                                             ***//
  //***************************************************************************************************//
  class Ticket
  {
    private readonly string ticketID;
    private readonly DateTime timeStamp;

    public Ticket(string tid)
    {
      ticketID = tid;
      timeStamp = DateTime.Now;
    }

    public override string ToString()
    {
      return String.Format("Ticket ID : {0}\nTimestamp : {1}\n", ticketID, timeStamp.ToString());
    }
  }


  //***************************************************************************************************//
  //***                                                                                             ***//
  //*** The TicketFactory class generates a new sequence of tickets on a separate thread. The       ***//
  //*** generation of the sequence is initiated by the TicketSubscribe method which will be passed  ***//
  //*** to Observable.Create().                                                                     ***//
  //***                                                                                             ***//
  //*** TicketSubscribe() provides the IDisposable interface used to dispose of the subscription    ***//
  //*** stopping ticket generation resources.                                                       ***//
  //***                                                                                             ***//
  //***************************************************************************************************//
  public class TicketFactory : IDisposable
  {
    private bool bGenerate = true;


    internal TicketFactory(object ticketObserver)
    {
      //************************************************************************//
      //*** The sequence generator for tickets will be run on another thread ***//
      //************************************************************************//
      Task.Factory.StartNew(new Action<object>(TicketGenerator), ticketObserver);
    }


    //**************************************************************************************************//
    //*** Dispose frees the ticket generating resources by allowing the TicketGenerator to complete. ***//
    //**************************************************************************************************//
    public void Dispose()
    {
      bGenerate = false;
    }


    //*****************************************************************************************************************//
    //*** TicketGenerator generates a new ticket every 3 sec and calls the observer's OnNext handler to deliver it. ***//
    //*****************************************************************************************************************//
    private void TicketGenerator(object observer)
    {
      IObserver<Ticket> ticketObserver = (IObserver<Ticket>)observer;

      //***********************************************************************************************//
      //*** Generate a new ticket every 3 sec and call the observer's OnNext handler to deliver it. ***//
      //***********************************************************************************************//
      Ticket t;

      while (bGenerate)
      {
        t = new Ticket(Guid.NewGuid().ToString());
        ticketObserver.OnNext(t);
        Thread.Sleep(3000);
      }
    }



    //********************************************************************************************************************************//
    //*** TicketSubscribe starts the flow of tickets for the ticket sequence when a subscription is created. It is passed to       ***//
    //*** Observable.Create() as the subscribe parameter. Observable.Create() returns the IObservable<Ticket> that is used to      ***//
    //*** create subscriptions by calling the IObservable<Ticket>.Subscribe() method.                                              ***//
    //***                                                                                                                          ***//
    //*** The IDisposable interface returned by TicketSubscribe is returned from the IObservable<Ticket>.Subscribe() call. Calling ***//
    //*** Dispose cancels the subscription freeing ticket generating resources.                                                    ***//
    //********************************************************************************************************************************//
    public static IDisposable TicketSubscribe(object ticketObserver)
    {
      TicketFactory tf = new TicketFactory(ticketObserver);

      return tf;
    }
  }
}

Veja a seguir um exemplo de saída do código de exemplo. Pressione Enter para cancelar o registro.

Press ENTER to unsubscribe...

Ticket ID : a5715731-b9ba-4992-af00-d5030956cfc4
Timestamp : 5/18/2011 6:48:50 AM

Ticket ID : d9797b2b-a356-4928-bfce-797a1637b11d
Timestamp : 5/18/2011 6:48:53 AM

Ticket ID : bb01dc7d-1ed5-4ba0-9ce0-6029187792be
Timestamp : 5/18/2011 6:48:56 AM

Ticket ID : 0d3c95de-392f-4ed3-bbda-fed2c6bc7287
Timestamp : 5/18/2011 6:48:59 AM

Ticket ID : 4d19f79e-6d4f-4fec-83a8-9644a1d4e759
Timestamp : 5/18/2011 6:49:05 AM

Consulte Também

Referência

Classe Observável

Criar sobrecarga

System.Reactive.Linq Namespace