Madhur Ahuja
Madhur Ahuja

Reputation: 22701

Ordering http API Calls in Android

Let me first explain my problem:

We are using HTTP REST protocol to transmit chat messages. For chat messages, ordering of messages is critical. Since HTTP is a stateless protocol, we are observing that messages are received out of order on server.

For example, if we send A, B and C - received order on server can be C, B and A.

Is there a way to solve this? I am not sure if HTTP requests can be ordered in Android. Even if we try to do so, that might reduce its efficiency since only single HTTP request will be executing at a time.

Is there any established pattern to solve this?

Upvotes: 0

Views: 88

Answers (2)

inmyth
inmyth

Reputation: 9060

In my case I assigned timestamp on each request and then saved them on my db. Users may see their messages unordered especially when they chat very fast. But when they refresh, the server will return the ordered list based on the timestamp registered.

Upvotes: 1

Dimitar Darazhanski
Dimitar Darazhanski

Reputation: 2326

The reason they arrive in an unpredictable order is because such is the nature of networking. Packets travel through different routing points and you cannot force them to be in order. Even if you send them in order, they are not guaranteed to arrive in order. But the good news is you can achieve what you are looking for in several different ways.

  1. You can wait for the server to respond back with OK, before you submit the next message. That will ensure the order, but you would lose the multithreading.
  2. A better solution would be to tag each message with an order_id or a timestamp. Then the server puts them in order.

Upvotes: 2

Related Questions