When the server sends one return value at a time the client can call a callback for every item if the server function is called using the GetDownStreamController<TDown> function.
GetDownStreamController's return value is a DownStreamItemController<TDown> that implements the IFuture<TResult> interface. With DownStreamItemController's OnItem function it can be subscribed for a callback that will be called for every downloaded item. The instance of DownStreamItemController<TDown> can be used to cancel the streaming:
varcontroller=hub.GetDownStreamController<int>("ChannelCounter",10,1000);controller.OnItem(result=>Debug.log("New item arrived: "+result.ToString())).OnSuccess(_=>Debug.log("Streaming finished!")).OnError(error=>Debug.log("Error: "+error));// A stream request can be cancelled any time by calling the controller's Cancel methodcontroller.Cancel();
GetUpStreamController is a generic function, its first type-parameter is the return type of the function then 1-5 types can be added as parameter types. The GetUpStreamController call returns an UpStreamItemController instance that can be used to upload parameters (UploadParam), Finish or Cancel the uploading.
It also implements the IDisposable interface so it can be used in a using statement and will call Finish when disposed. Here's the previous sample using the IDisposable pattern:
publicclassUploadHub:Hub{publicasyncTask<string>UploadWord(ChannelReader<string>source){varsb=newStringBuilder();// receiving a StreamCompleteMessage should cause this WaitToRead to return falsewhile(awaitsource.WaitToReadAsync()){while(source.TryRead(outvaritem)){Debug.WriteLine($"received: {item}");Console.WriteLine($"received: {item}");sb.Append(item);}}// method returns, somewhere else returns a CompletionMessage with any errorsreturnsb.ToString();}}
After using GetDownStreamController to stream results from the server and GetUpStreamController to stream parameters to the server, there's a third one to merge these two's functionality, the GetUpAndDownStreamController function. With its help we can stream parameters to a server-side function just like with GetUpStreamController and stream down its result to the client like we can with GetDownStreamController.
using(varcontroller=hub.GetUpAndDownStreamController<string,string>("StreamEcho")){controller.OnSuccess(_=>{Debug.log("Finished!");});controller.OnItem(item=>{Debug.log("On Item: "+item);});constintnumMessages=5;for(inti=0;i<numMessages;i++){yieldreturnnewWaitForSeconds(_yieldWaitTime);controller.UploadParam(string.Format("Message from client {0}/{1}",i+1,numMessages));}yieldreturnnewWaitForSeconds(_yieldWaitTime);}
GetUpAndDownStreamController also returns with an UpStreamItemController instance, but in this case its OnItem can be used too. The callback passed to the OnItem call will be called for every item the server sends back to the client.