Continue to receive fresh activities for finished requests in rsocket

Given a scenario where an Rsocket endpoint is set up using Spring,

    @MessageMapping("chat.{chatId}")
    Flux<Message> getChats(@DestinationVariable String chatId) {
        Mono<Chat> data = chatRepository.findById(chatId);
        return data.map(chatGroup -> chatGroup.getMessages())
                .flatMapMany(Flux::fromIterable);
    }


   public interface ChatRepository extends FirestoreReactiveRepository<Chat> {

   }

a client connects to it via websocket through JS (Rsocket 1.x)

const makeConnector = () => {
      return new RSocketConnector({
        setup: {
          dataMimeType: 'application/json',
          keepAlive: 100000,
          lifetime: 100000,
          metadataMimeType: 'message/x.rsocket.routing.v0',
        },
        transport: new WebsocketClientTransport({
          url: 'ws://localhost:7000/rsocket',
        }),
      });
};

client()
  .connect()
  .then((socket) => {
    const requester = socket.requestStream(
      {
        data: undefined,
        metadata: Buffer.concat([
          Buffer.from(String.fromCharCode('chat.chatId'.length)),
          Buffer.from('chat.chatId'),
        ]),
      },
      10,
      {
        onError: (e) => console.log('error getting data', e),
        onNext: (payload, isComplete) => {
          const parsedData: Chat = JSON.parse(payload.data.toString());
          requester.request(5); // request the next 5 chats
        },
        onComplete: () => {
          console.log('complete');
        },
        onExtension: () => {
          console.log('on extension');
        },
      }
    );
  });

After the requestStream data is completed, such as when 'complete' is printed in console,

new events are no longer received. Is there a way to listen to new events even after a stream is completed?

I attempted using intervals to work around this issue, but it led to receiving duplicate chats. Filtering them on the frontend side is a solution, but I believe there must be a better approach

return Flux.interval(Duration.ofSeconds(5)).flatMap(x -> {
   return chatService.findChats(matchId);
});

Answer №1

RSocket-JS doesn't have a built-in mechanism for re-subscribing when a connection is closed. This means that once your connection is closed or completed, you won't be able to receive events on that connection anymore.

In RSocket, if the WebSocket connection status changes to 'CLOSED' or 'ERROR', the subscription is automatically cancelled, preventing any new events from being received.

You can see this behavior in their RSocketClient.js file, specifically on line 91: https://github.com/rsocket/rsocket-js/blob/master/packages/rsocket-core/src/RSocketClient.js

If you want to continue receiving new events after your current connection has been closed, you'll need to establish a new connection. You can refer to the example provided by RSocket here: https://github.com/rsocket/rsocket-js/blob/master/packages/rsocket-examples/src/ReconnectExample.js

Personally, I have implemented this feature in a project I'm currently working on, but with some modifications. These include setting a maximum number of retry attempts and introducing an exponential time interval before each retry, along with some randomness to prevent all WebSocket clients from reconnecting simultaneously and overwhelming the server with requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

While attempting to run the project I downloaded from GitHub using the command npm run serve, I encountered the following error: "Syntax Error: Error: No ESLint configuration found in

After receiving a Vue.js project from GitHub, I attempted to download and run it. However, when I tried the command npm run serve, I encountered an error message: Syntax Error: Error: No ESLint configuration found in C:\Users\User\Desktop&bs ...

Pattern matching with a 4-block sequence along with specified minimum and maximum lengths using regular expressions

I have created a formula that follows a unique 4-Block format (e.g. 1232 2131 3233 2323 23). My goal is to validate an input String against this pattern, but with a maximum length requirement. I have managed to create a regex for a fixed length....e.g. & ...

Verify in JavaScript whether the object from the session exists

Within View.cshtml, there is a section where I am checking for the existence of an object named Reservation in the session. <head> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryval") <script type="text/javascri ...

Retrieving the value of a radio button using JavaScript

I am working with dynamically generated radio buttons that have been given ids. However, when I attempt to retrieve the value, I encounter an issue. function updateAO(id2) { var status = $('input[name=id2]:checked').val(); alert(status); ...

Error: An unanticipated string was encountered in NextJS 13

I have a single static generator (SSG) page structured as follows: /* imports...... */ export default async function Page({ params: { page }, searchParams }) { const queryParams = new URLSearchParams(searchParams) const count = await getPag ...

The else if statement is not functioning as anticipated

I am looking for a toggle function that will open and close a <div> when clicked. Check out this JSFiddle HTML <div class='answer'>answer</div> <div style='display:none'> <textarea name='talking&a ...

The presence of 'touched' within Angular validation is causing a delay in method execution

Upon utilizing this validation method, it became apparent: <label>Password</label> <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': f.password.touc ...

Is there a way to incorporate a variable into a JSON URL?

I'm attempting to incorporate a variable I have defined into the JSON URL: var articleName = "test"; $.getJSON( "https://www.googleapis.com/customsearch/v1?key=API_MY&cx=CX_MY&q='+articleName+'&searchType=image&fileType= ...

Using ESM imports in webpack configuration

I'm in the process of creating a webpack application and I am keen on utilizing ESM (ECMAScript Modules) throughout the entire project. This involves configuring the webpack.config file to allow for ESM imports. Previously, I knew that this could be ...

What causes npm start to fail with a CORS error, but run successfully with HOST=127.0.0.1 npm start?

Currently, I am in the process of creating a basic application that utilizes Flask for the backend and React for the frontend. An issue arises when attempting to initiate my React application through npm start, as it triggers a CORS error. Strangely enough ...

You are unable to create an EnumMap using a dynamic class argument for enums that contain methods

While working with enums in Java, I discovered an interesting difference in behavior between those without any defined methods and those that have them. In the latter case, Enum.class and Enum.getClass() actually point to different compiled classes, result ...

Why does the second JavaScript form validation not function correctly when compared to the first?

Here is a form that I have created: <form action="next.html" id="userInput" method="post" onsubmit="return validate();"> Age: <input type="text" name="age" id="age"/> function validate() { var age = document. ...

What are the methods for determining if a Triangle intersects a Box3?

Is there a built-in function in THREE.js to determine if a THREE.Triangle overlaps with a THREE.Box3 object? If not, what approach can be taken to achieve this? ...

ERROR OCCURRED DURING DEPLOYMENT of jboss version 5.1.0

2017-02-08 16:58:54,022 INFO [org.jboss.web.tomcat.service.deployers.TomcatDeployment] (main) deploy, ctxPath=/IAPFxStruts 2017-02-08 16:58:54,060 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/IAPFxStruts]] (main ...

Unable to assign an ID to an event in Angular when the eventReceived event is triggered

I am currently working with the Angular fullcalendar module that includes drag and drop functionality. My goal is to assign an ID to new events dropped on the calendar by users, but I am unsure of the proper way to do this. Here is the Stackblitz link. Ad ...

In React hooks, Socket.io has a strange behavior where it adds users multiple times with varying socket IDs

Encountering an issue with my React and Socket.IO application. Upon a user joining a room, their information is being duplicated in the client's array on the client side. Despite having the same username, the entries have different socket IDs assigned ...

Adjust the constant state in one component using another component

I created a React application with a simple menu that switches state when clicked to open and close it. The functionality works as expected with the menu button located within the same component. However, I now face a challenge in trying to open the menu f ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

Retrieving attributes of elements within an ArrayList

Seeking help to create a method that calculates the total sum of rectangle areas within a designated ArrayList. public class Homework { public static void main(String[] args) { ArrayList<Rectangle> test = new ArrayList<Rectangle>(); te ...

JS - what could be causing this to not work properly? Could there be a bug that

Can anyone help me troubleshoot this code? It is supposed to add a search parameter page=value to the URL and load the page, but it's not working. I'm not sure if there's a typo in there. $(function(){ $('.page').on('cl ...