SignalR streaming from server to client

Viewed 1194

I can't get my server to stream data to a client with SignalR. The stream only gets 1 value, 0 in this case, then falls back to the javascript complete callback method. Need some help to figure out why it doesn't work. Here are the Hub code and the JS code:

public class ChatHub : Hub
    {
        private Channel<double> channel = Channel.CreateUnbounded<double>();

        public async IAsyncEnumerable<double> GetData(CancellationToken cancellationToken)
        {
            while (await channel.Reader.WaitToReadAsync())
            {
                while (channel.Reader.TryRead(out var item))
                {
                    yield return item;
                }
            }
        }

        public async Task PublishData(IAsyncEnumerable<double> data)
        {
            await foreach (var point in data)
            {
                await channel.Writer.WriteAsync(point);
            }
        }
    }

JS:

(async () => {

        const latestNumber = 0;
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .build();

        await connection.start();

        connection.stream("GetData")
            .subscribe({
                next: (item) => {
                    var li = document.createElement("li");
                    li.textContent = item;
                    document.getElementById("messagesList").appendChild(li);
                },
                complete: () => {
                    var li = document.createElement("li");
                    li.textContent = "Stream completed";
                    document.getElementById("messagesList").appendChild(li);
                },
                error: (err) => {
                    var li = document.createElement("li");
                    li.textContent = err;
                    document.getElementById("messagesList").appendChild(li);
                },
            });

        console.log(latestNumber);

    })();
1 Answers

I found the answer, made a service class singleton and added the channel into that. Then i called the singleton class from the hub so i get the same instance of the channel between server and client.

Related