private static IEnumerable <EventBase> DoWork( ILogger logger, IConsumer <Ignore, string> consumer, CancellationToken token) { while (!token.IsCancellationRequested) { ConsumeResult <Ignore, string> consumeResult; try { consumeResult = consumer.Consume(token); } catch (OperationCanceledException) { // ignore yield break; } catch (ConsumeException e) { logger.LogError(e, "Unable to consume event(s)."); throw; } EventBase @event; try { @event = KafkaEventListener.TranslateJson(consumeResult.Message.Value); } catch (JsonException) { logger.LogError($"Failed to deserialize event: \"{consumeResult.Message.Value}\"."); throw; } yield return(@event); } }
public void StartListening() { if (this.token != null && !this.token.IsCancellationRequested) { throw new InvalidOperationException("Already listening."); } this.token = new CancellationTokenSource(); this.task = Task.Run( () => { foreach (var eventBase in KafkaEventListener.DoWork(this.logger, this.consumer, this.token.Token)) { this.subject.OnNext(eventBase); } }, this.token.Token) .ContinueWith( prevTask => { this.consumer.Unsubscribe(); if (prevTask.IsFaulted) { this.subject.OnError(prevTask.Exception); } else { this.subject.OnCompleted(); } this.task = null; }); this.consumer.Subscribe(this.configuration.Topics.Select(x => x.Value)); }