aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Transport/TransportMessage.cs
blob: ef2505848d44fd1949a950960b7b8c223bfd32b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;
using Tango.PMR;

namespace Tango.Transport
{
    /// <summary>
    /// Represents a generic transport message.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="Tango.Transport.TransportMessageBase" />
    internal class TransportMessage<T> : TransportMessageBase
    {
        private TaskCompletionSource<T> _completionSource;

        public Subject<T> ContinuesResponseSubject { get; set; }

        public bool AtLeastOneResponseReceived { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TransportMessage{T}"/> class.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <param name="message">The message.</param>
        /// <param name="direction">The direction.</param>
        /// <param name="toBytes">To bytes.</param>
        /// <param name="completionSource">The completion source.</param>
        public TransportMessage(string token, object message, TransportMessageDirection direction, Func<byte[]> toBytes, TaskCompletionSource<T> completionSource) : base(token, message, direction, toBytes)
        {
            _completionSource = completionSource;
        }

        /// <summary>
        /// Notifies the message observer of the new result.
        /// </summary>
        /// <param name="result">The result.</param>
        public override void SetResult(object result, bool completed)
        {
            if (!IsContinuous)
            {
                _completionSource.SetResult((T)result);
            }
            else
            {
                AtLeastOneResponseReceived = true;
                ContinuesResponseSubject.OnNext((T)result);

                if (completed)
                {
                    ContinuesResponseSubject.OnCompleted();
                }
            }
        }

        /// <summary>
        /// Notifies the message observer of an exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        public override void SetException(Exception ex)
        {
            if (!IsContinuous)
            {
                _completionSource.SetException(ex);
            }
            else
            {
                AtLeastOneResponseReceived = true;
                ContinuesResponseSubject.OnError(ex);
            }
        }
    }
}