Please be aware that you are viewing our bleeding edge unstable documentation. Unless you wanted to view the bleeding edge (and possibly unstable) documentation, we recommend you use our stable docs.

Go to Ably's stable canonical documentation »

I know what I'm doing, let me see the bleeding edge docs »

You are viewing our bleeding edge unstable documentation. We recommend you use our stable documentation »
Fork me on GitHub

Channels and Messages

The Ably Realtime service organizes the message traffic within applications into named channels. Channels are the “unit” of message distribution; clients attach to channels to subscribe to messages, and every message published to a unique channel is broadcast by Ably to all subscribers. This scalable and resilient messaging pattern is commonly called pub/sub.

Getting started

The Ably REST client library provides a straightforward API for publishing and retrieve history messages on a channel.

var rest = new Ably.Rest('{{API_KEY}}');
var channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}');
channel.publish('example', 'message data', function() {
  channel.history(function(err, resultPage) {
    console.log('Last published message:' + resultPage.items[0]);
  });
});
var rest = new Ably.Rest('{{API_KEY}}');
var channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}');
channel.publish('example', 'message data', function() {
  channel.history(function(err, resultPage) {
    console.log('Last published message:' + resultPage.items[0]);
  });
});
rest = Ably::Rest.new('{{API_KEY}}')
channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}')
channel.publish 'example', 'message data'
result_page = channel.history()
puts "Last published message: #{result_page.items.first}"
rest = AblyRest('{{API_KEY}}')
channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}')
channel.publish(u'example', u'message data')
result_page = channel.history()
print("Last published message data: " + result_page.items[0].data)
$rest = new Ably\AblyRest('{{API_KEY}}');
$channel = $rest->channels->get('{{RANDOM_CHANNEL_NAME}}');
$channel->publish('example', 'message data');
$resultPage = $channel->history();
echo("Last published data: " . $resultPage->items[0]->data);
AblyRest rest = new AblyRest("{{API_KEY}}");
Channel channel = rest.channels.get("{{RANDOM_CHANNEL_NAME}}");
channel.publish("example", "message data");
PaginatedResult<Message> resultPage = channel.history(null);
System.out.println("Last published message ID: " + resultPage.items[0].id);
AblyRest rest = new AblyRest("{{API_KEY}}");
var channel = rest.Channels.Get("{{RANDOM_CHANNEL_NAME}}");
await channel.PublishAsync("example", "message data");
PaginatedResult<Message> resultPage = await channel.HistoryAsync();
Console.WriteLine("Last published message ID: " + resultPage.Items[0].id);
ARTRest *rest = [[ARTRest alloc] initWithKey:@"{{API_KEY}}"];
ARTRestChannel *channel = [rest.channels get:@"{{RANDOM_CHANNEL_NAME}}"];
[channel publish:@"example" data:@"message data"];
[channel history:^(ARTPaginatedResult<ARTMessage *> *resultPage, ARTErrorInfo *error) {
    NSLog(@"Last published message ID: %@", resultPage.items[0].id);
}];
let rest = ARTRest(key: "{{API_KEY}}")
let channel = rest.channels.get("{{RANDOM_CHANNEL_NAME}}")
channel.publish("example", data: "message data")
channel.history { resultPage, error in
    print("Last published message ID: \(resultPage!.items[0].id)")
}

If you would prefer to just dive into code and see some examples of how to use channels and messages, then we recommend you take a look at our REST tutorials.

Channels

In order to publish, retrieve message history or access presence history, you must first obtain a REST channel instance.

Obtaining a channel instance

A Channel object is a reference to a single channel. A channel instance is obtained from the channels collection of the Rest::ClientAblyRestRest instance, and is uniquely identified by its unicode string name. Find out more about channel naming

var channel = rest.channels.get('channelName');
var channel = rest.channels.get('channelName');
Channel channel = rest.channels.get("channelName");
Channel channel = rest.Channels.Get("channelName");
channel = rest.channels.get('channelName')
channel = rest.channels.get('channelName')
$channel = $rest->channels->get('channelName');
ARTRestChannel *channel = [realtime.channels get:@"channelName"];
let channel = realtime.channels.get("channelName")

To find out more about subscribing to messages published on channels in realtime, see the Realtime channel API.

Setting channel options and encryption

A set of channel options may also be passed to configure a channel for encryption. Find out more about symmetric message encryption.

Crypto.generateRandomKey(function(err, key) {
  var options = { cipher: { key: key } };
  var channel = rest.channels.get('channelName', options);
});
Crypto.generateRandomKey(function(err, key) {
  var options = { cipher: { key: key } };
  var channel = rest.channels.get('channelName', options);
});
CipherParams params = Crypto.getDefaultParams(key);
ChannelOptions options = new ChannelOptions();
options.encrypted = true;
options.cipherParams = params;
Channel channel = rest.channels.get("channelName", options);
CipherParams cipherParams = Crypto.GetDefaultParams(key);
var options = new ChannelOptions(cipherParams);
var encryptedChannel = rest.Channels.Get("channelName", options);
key = Ably::Util::Crypto.generate_random_key
options = { cipher: { key: key } }
channel = rest.channels.get('channelName', options)
key = ably.util.crypto.generate_random_key()
channel = rest.channels.get('channelName', cipher={'key': key})
$key = Ably\Crypto->generate_random_key();
$options = array('cipher' => array('key' => key));
$channel = $rest->channels->get('channelName', $options);
NSData *key = [ARTCrypto generateRandomKey];
ARTChannelOptions *options = [[ARTChannelOptions alloc] initWithCipherKey:key];
ARTRestChannel *channel = [rest.channels get:@"channelName" options:options];
let key = ARTCrypto.generateRandomKey()
let options = ARTChannelOptions(cipherKey: key)
let channel = rest.channels.get("channelName", options: options)

Channel namespaces

One or more channel namespaces, or channel name prefixes, may be configured for an app in your dashboard. When a channel is created whose name is prefixed with one of the namespaces, the channel assumes certain configured attributes associated with that namespace. For example, a channel namespace named “private” would match channels named “private”, “private:chat”, “private:chat:mike”.

Namespace-prefixed channel names are delimited by a single colon :; the first component of the channel name (from the start up to and including the last character before the colon) is the namespace. A channel name may validly contain a colon even if the namespace component does not correspond to a namespace; also, a channel may contain multiple colons and only the component up to the first colon will be matched with a namespace. The only restriction on channel names is that a channel name may not start with a colon :, an open square bracket [ and it may not be empty.

Namespaces are defined and configured via the application dashboard settings. The namespace attributes that can be configured are:

Key or token capabilities can also specify access rights based on channel namespace, find out more about authentication

Messages

Each message published has an optional event name propertymemberattribute and a data propertymemberattribute carrying the payload of the message. Various primitive and object types are defined, portable and supported in all clients, enabling clients to be interoperable despite being hosted in different languages or environments.

The supported payload types are Strings, JSON objects and arrays, plain c# objects which are converted to json, buffers containing arbitrary binary data, and Null objects. Client libraries detect the supplied message payload and encode the message appropriately.

Subscribing to messages

The REST client library does not offer message realtime subscription but instead provides access to the “live” history using the REST history API. Find out more about subscribing to messages in realtime using the Realtime API.

The name propertymemberattribute of published messages does not affect the distribution of a channel message to clients but may be used as a subscription filter, allowing a client to register a listener that only sees a subset of the messages received on the channel. Find out more about registering listeners using the Realtime API.

Publishing messages

Channels expose a publish method whereby a client can publish either a single message or an array of messages to a channel over REST.

channel.publish('event', 'This is my payload', function(err) {
  if(err) {
    console.log('Unable to publish message; err = ' + err.message);
  } else {
    console.log('Message successfully sent');
  }
});
channel.publish('event', 'This is my payload', function(err) {
  if(err) {
    console.log('Unable to publish message; err = ' + err.message);
  } else {
    console.log('Message successfully sent');
  }
});
channel.publish('event', 'This is my payload')
channel.publish(u'event', u'This is my payload')
$channel->publish('event', 'This is my payload');
channel.publish("event", "This is my payload");
channel.PublishAsync("event", "This is my payload");
[channel publish:@"event" data:@"This is my payload"];
channel.publish("event", data: "This is my payload")

Publishing on behalf of realtime connection

Message published using the REST API may be done so on behalf of an existing realtime connection when a valid connectionKey is present in the published message. For example, if you want to publish a message using the REST client library so that it appears to come from an existing connected realtime client, then the connection’s private (secret) connection key must be included. See a publish on behalf of a realtime client example.

If the connectionKey is invalid or belongs to a connection that has since been closed, then the publish operation will fail.

Retrieving message history

Channels expose a historyHistory method providing a means for clients to obtain messages previously sent on the channel. Channel history can be used to return continuous message history up to the exact point a realtime channel was attached.

History provides access to instantaneous “live” history as well as the longer term persisted history for attached channels. If persisted history is enabled for the channel, then messages will typically be stored for 24 – 72 hours. If persisted history is not enabled, Ably retains the last two minutes of message history in memory.

The following example retrieves the first two pages of historical messages published up until the point the channel was attached.

channel.history(function(err, resultPage) {
  if(err) {
    console.log('Unable to get channel history; err = ' + err.message);
  } else {
    console.log(resultPage.items.length + ' messages received in first page');
    if(resultPage.hasNext()) {
      resultPage.next(function(err, nextPage) { ... });
    }
  }
});
channel.history(function(err, resultPage) {
  if(err) {
    console.log('Unable to get channel history; err = ' + err.message);
  } else {
    console.log(resultPage.items.length + ' messages received in first page');
    if(resultPage.hasNext()) {
      resultPage.next(function(err, nextPage) { ... });
    }
  }
});
PaginatedResult<Message> resultPage = channel.history(null);
System.out.println(resultPage.items().length + " messages received in first page");
if(resultPage.hasNext()) {
  PaginatedResult<Message> nextPage = resultPage.next();
  System.out.println(nextPage.items().length + " messages received in second page");
}
PaginatedResult<Message> resultPage = await channel.HistoryAsync();
Console.WriteLine(resultPage.Items.Count + " messages received in first page");
if(resultPage.HasNext) {
  PaginatedResult<Message> nextPage = await resultPage.NextAsync();
  Console.WriteLine(nextPage.Items.Count + " messages received in second page");
}
result_page = channel.history
puts "#{result_page.items.length} messages received in first page"
if result_page.has_next?
  next_page = result_page.next
  puts "#{next_page.items.length} messages received in second page"
end
result_page = channel.history()
print str(len(result_page.items)) + ' messages received in first page'
if result_page.has_next():
  next_page = result_page.next()
  print str(len(next_page.items)) + ' messages received in second page'
$resultPage = channel->history();
echo(count($resultPage->items) . 'messages received in first page');
if($resultPage->hasNext()) {
  $nextPage = $resultPage.next();
  echo(count($resultPage->items) . 'messages received in second page');
}
[channel history:^(ARTPaginatedResult<ARTMessage *> *resultPage, ARTErrorInfo *error) {
  NSLog(@"%lu messages received in first page", (unsigned long)[resultPage.items count]);
  if (resultPage.hasNext) {
    [resultPage next:^(ARTPaginatedResult<ARTMessage *> *nextPage, ARTErrorInfo *error) {
      // ...
    }];
  }
}];
channel.history { resultPage, error in
  let resultPage = resultPage!
  print("\(resultPage.items.count) messages received in first page")
  if resultPage.hasNext {
    resultPage.next { nextPage, error in
      // ...
    }
  }
}

See the history documentation for further details of the supported query parameters.

Presence

Channels expose a presencePresence member which a client can use to obtain present members and presence event history for the channel itself. See the REST presence documentation for details.

Channel API Reference

Channel PropertiesChannel AttributesAbly\Channel PropertiesARTRestChannel PropertiesAbly::Rest::Channel Attributesio.ably.lib.rest.Channel MembersIO.Ably.Rest.RestChannel Members

The Channel object exposes the following public propertiesattributesmembers:

nameName

The name String unique to this channel.

presencePresence

Provides access to the REST Presence object for this channel which can be used to get members present on the channel, or retrieve presence event history.

Methods

publishPublish

There are two overloaded versions of this method:

publish(String name, Object data, callback(ErrorInfo err))publish(String name, Object data)publish(name=Unicode, data=Object)void publish(String name, Object data)Task PublishAsync(string name, object data, string clientId = null)publish(name: String?, data: AnyObject?, callback: ((ARTErrorInfo?) → Void)?)

Publish a single message on this channel based on a given event name and payload. A callbacklistener may optionally be passed in to this call to be notified of success or failure of the operation.

publish(Object[] messages, callback(ErrorInfo err))publish(Message[] messages)publish(messages=List<Message>)void publish(Message[] messages)Task PublishAsync(IEnumerable<Message> messages)publish(messages: [ ARTMessage ], callback: ((ARTErrorInfo?) → Void)?)

Publish several messages on this channel. A callbacklistener may optionally be passed in to this call to be notified of success or failure of the operation.

Parameters

name
event name for the published message
Type: StringType: Unicode for Python 2, String for Python 3
data
data payload for the message. The supported payload types are Strings, JSON objects and arrays, buffers containing arbitrary binary data, and null.
Type: Object
data
data payload for the message. The supported payload types are Strings, JsonObject, binary data as byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are strings, plain .Net objects, binary data as byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are Strings, Hash or Array objects that can be serialized to JSON using to_json, binary data as ASCII-8BIT byte arrays, and null.
Type: Object
data
data payload for the message. The supported payload types are unicode Strings, Dict, or List objects that can be serialized to JSON using json.dumps, binary data as bytearray (in Python 3, bytes also works), and None.
Type: Object
data
data payload for the message. The supported payload types are NSString, NSDictionary or NSArray objects that can be serialized to JSON, binary data as NSData, and nil.
Type: Object
data
data payload for the message. The supported payload types are Strings, Associative Array or Array objects that can be serialized to JSON, binary data as byte arrays, and null.
Type: Object
messages
An array of message objects to publish
Type: Message []
callback
is a function of the form function(err) which is called upon completion
callback
called upon publishing the message, or with an error

Callback result

On successful publish of the message, err is null. On failure to publish the message, err contains an ErrorInfo object describing the failure reason.

Failure

On failure to publish the message, an AblyException will be raised.

Returns

The method is asynchronous and returns a Task that can be awaited.

On failure to publish the message, an AblyException will be raised.

historyHistory

history(Object options, callback(ErrorInfo err, PaginatedResult<Message> resultPage))PaginatedResult<Message> history(Hash options)PaginatedResult<Message> history(kwargs_options)PaginatedResult<Message> history(Array options)PaginatedResult<Message> history(Param[] options)Task<PaginatedResult<Message>> HistoryAsync(HistoryRequestParams dataQuery)history(query: ARTRealtimeHistoryQuery?, callback: (ARTPaginatedResult<ARTMessage>?, ARTErrorInfo?) → Void) throws

Gets a paginated set of historical messages for this channel. If the channel is configured to persist messages to disk, then message history will typically be available for 24 – 72 hours. If not, messages are only retained in memory by the Ably service for two minutes.

Parameters

optionsqueryParam[] options
an optional object containing the query parametersoptional keyword arguments containing the query parametersan optional set of key value pairs containing the query parametersan optional Associative Array containing the query parameters, as specified in the message history API documentation.
callback
is a function of the form: function(err, resultPage)
callback
called with a ARTPaginatedResult<ARTMessage> object or an error

Callback result

On success, resultPage contains a PaginatedResult encapsulating an array of Message objects corresponding to the current page of results. PaginatedResult supports pagination using next() and first() methods.

On failure to retrieve message history, err contains an ErrorInfo object with the failure reason.

Returns

On success, the returned PaginatedResult encapsulates an array of Message objects corresponding to the current page of results. PaginatedResult supports pagination using next and first methods.

Failure to retrieve the message history will raise an AblyException

Returns

The method is asynchronous and return a Task that has to be awaited to get the result.

On success, the returned PaginatedResult encapsulates an array of Message objects corresponding to the current page of results. PaginatedResult supports pagination using NextAsync and FirstAsync methods.

Failure to retrieve the message history will raise an AblyException

MessageARTMessageAbly::Models::MessageAbly\Models\Messageio.ably.lib.types.MessageIO.Ably.Message

A Message represents an individual message that is sent to or received from Ably.

PropertiesMembersAttributesAttributes

nameName
Event name, if provided
Type: String
data
The message payload, if provided
Type: String, StringBuffer, JSON Object
data
The message payload, if provided
Type: String, ByteArray, JSONObject, JSONArray
Data
The message payload, if provided
Type: String, byte[], plain C# object that can be serialized to Json
data
The message payload, if provided
Type: String, Binary (ASCII-8BIT String), Hash, Array
data
The message payload, if provided
Type: String, Bytearray, Dict, List
data
The message payload, if provided
Type: String, Binary String, Associative Array, Array
data
The message payload, if provided
Type: NSString *, NSData *, NSDictionary *, NSArray *
data
The message payload, if provided
Type: String, NSData, Dictionary, Array
idId
Unique ID assigned by Ably to this message
Type: String
clientIdclient_idClientId
The client ID of the publisher of this message
Type: String
connectionIdconnection_idConnectionId
The connection ID of the publisher of this message
Type: String
timestampTimestamp
Timestamp when the presence update was received by the Ably the realtime service, as milliseconds since the epocha Time object
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
encodingEncoding
This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload
Type: String

Message constructors

Message.fromEncoded

Message.fromEncoded(Object encodedMsg, ChannelOptions channelOptions?) → Message

A static factory method to create a Message from a deserialized Message-like object encoded using Ably’s wire protocol.

Parameters

encodedMsg
a Message-like deserialized object.
Type: Object
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.
Type: Object

Returns

A Message object

Message.fromEncodedArray

Message.fromEncodedArray(Object[] encodedMsgs, ChannelOptions channelOptions?) → Message[]

A static factory method to create an array of Messages from an array of deserialized Message-like object encoded using Ably’s wire protocol.

Parameters

encodedMsgs
an array of Message-like deserialized objects.
Type: Array
channelOptions
an optional ChannelOptions. If you have an encrypted channel, use this to allow the library can decrypt the data.
Type: Object

Returns

An Array of Message objects

ChannelOptions ObjectARTChannelOptionsChannelOptions HashChannelOptions keyword argumentsChannelOptions Arrayio.ably.lib.types.ChannelOptionsIO.Ably.ChannelOptions

Currently the supported channel options are only used for configuring encryption.

ChannelOptions, a plain Javascript object, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following attributes can be defined on the object:

ChannelOptions, a Hash object, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following key symbol values can be added to the Hash:

ChannelOptions, an Associative Array, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following named keys and values can be added to the Associated Array:

ARTio.ably.lib.types.ChannelOptions may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options.

IO.Ably.ChannelOptions may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options.

PropertiesMembersAttributes

cipher:cipherCipherParams
Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an example
Type: CipherParams or an options objecta Param[] listan options hashan Associative Array containing at a minimum a key

Static methods

withCipherKey

static ChannelOptions.withCipherKey(Byte[] or String key)

A helper method to generate a ChannelOptions for the simple case where you only specify a key.

Parameters

key
A binary Byte[] array or a base64-encoded String.

Returns

On success, the method returns a complete ChannelOptions object. Failure will raise an AblyException.

HistoryRequestParams

HistoryRequestParams is a type that encapsulates the parameters for a history queries. For example usage see Channel#historyChannel#History.

Members

Start
null The start of the queried interval
Type: DateTimeOffset
End
null The end of the queried interval
Type: DateTimeOffset
Limit
null By default it is null. Limits the number of items returned by history or stats
Type: Integer
Direction
Backwards Enum which is either Forwards or Backwards
Type: Direction enum
ExtraParameters
Optionally any extra query parameters that may be passed to the query. This is mainly used internally by the library to manage paging.
Type: Dictionary<string, string>

PaginatedResultARTPaginatedResultAbly::Models::PaginatedResultAbly\Models\PaginatedResultio.ably.lib.types.PaginatedResultIO.Ably.PaginatedResult

A PaginatedResult is a type that represents a page of results for all message and presence history, stats and REST presence requests. The response from a Ably REST API paginated query is accompanied by metadata that indicates the relative queries available to the PaginatedResult object.

PropertiesMembersAttributes

itemsItems
contains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request)
Type: Array <Message, Presence, Stats>Type: List <Message, Presence, Stats>

Methods

firstFirst

first(callback(ErrorInfo err, PaginatedResult resultPage))PaginatedResult firstPaginatedResult first()PaginatedResult first()Task<PaginatedResult> FirstAsync()PaginatedResult first()first(callback: (ARTPaginatedResult?, ARTErrorInfo?) → Void)

Returns a new PaginatedResult for the first page of results. When using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.The method is asynchronous and returns a Task which needs to be awaited to get the PaginatedResult.

hasNextHasNexthas_next?has_next

Boolean hasNext()Boolean has_next?Boolean hasNext()Boolean has_next()Boolean HasNext()Boolean hasNext()Boolean hasNext()

Returns true if there are more pages available by calling nextNext and returns false if this page is the last page available.

isLastIsLastlast?is_last

Boolean isLast()Boolean last?Boolean isLast()Boolean is_last()Boolean IsLast()Boolean isLast()Boolean isLast()

Returns true if this page is the last page and returns false if there are more pages available by calling nextNext available.

nextNext

next(callback(ErrorInfo err, PaginatedResult resultPage))PaginatedResult nextPaginatedResult next()PaginatedResult next()Task<PaginatedResult> NextAsync()PaginatedResult next()next(callback: (ARTPaginatedResult?, ARTErrorInfo?) → Void)

Returns a new PaginatedResult loaded with the next page of results. If there are no further pages, then nulla blank PaginatedResult will be returnedNullNonenil is returned. The method is asynchronous and return a Task which needs to be awaited to get the PaginatedResultWhen using the Realtime library, the first method returns a Deferrable and yields a PaginatedResult.

Example

channel.history(function(err, paginatedResult) {
  console.log('Page 0 item 0:' + paginatedResult.items[0].data);
  paginatedResult.next(function(err, nextPage) {
    console.log('Page 1 item 1: ' + nextPage.items[1].data);
    console.log('Last page?: ' + nextPage.isLast());
  });
});
channel.history(function(err, paginatedResult) {
  console.log('Page 0 item 0:' + paginatedResult.items[0].data);
  paginatedResult.next(function(err, nextPage) {
    console.log('Page 1 item 1: ' + nextPage.items[1].data);
    console.log('Last page?: ' + nextPage.isLast());
  });
});
PaginatedResult firstPage = channel.history();
System.out.println("Page 0 item 0:" + firstPage.items[0].data);
if (firstPage.hasNext) {
  PaginatedResult nextPage = firstPage.next();
  System.out.println("Page 1 item 1:" + nextPage.items[1].data);
  System.out.println("More pages?:" + Strong.valueOf(nextPage.hasNext()));
};
PaginatedResult<Message> firstPage = await channel.HistoryAsync(null);
Message firstMessage = firstPage.Items[0];
Console.WriteLine("Page 0 item 0: " + firstMessage.data);
if (firstPage.HasNext)
{
    var nextPage = await firstPage.NextAsync();
    Console.WriteLine("Page 1 item 1:" + nextPage.Items[1].data);
    Console.WriteLine("More pages?: " + nextPage.HasNext());
}
# When using the REST sync library
first_page = channel.history
puts "Page 0 item 0: #{first_page.items[0].data}"
if first_page.has_next?
  next_page = first_page.next
  puts "Page 1 item 1: #{next_page.items[1].data}"
  puts "Last page?: #{next_page.is_last?}"
end

# When using the Realtime EventMachine library
channel.history do |first_page|
  puts "Page 0 item 0: #{first_page.items[0].data}"
  if first_page.has_next?
    first_page.next do |next_page|
      puts "Page 1 item 1: #{next_page.items[1].data}"
      puts "Last page?: #{next_page.is_last?}"
    end
  end
end
result_page = channel.history()
print 'Page 0 item 0: ' + str(result_page.items[0].data)
if result_page.has_next():
  next_page = result_page.next()
  print 'Page 1 item 1: ' + str(next_page.items[1].data)
  print 'Last page?: ' + str(next_page.is_last())
$firstPage = $channel.history();
echo("Page 0 item 0: " . $firstPage->items[0]->data);
if ($firstPage->hasNext()) {
  $nextPage = $firstPage->next();
  echo("Page 1 item 1: " . $nextPage->items[1]->data);
  echo("Last page?: " . $nextPage->isLast());
}
[channel history:^(ARTPaginatedResult<ARTMessage *> *paginatedResult, ARTErrorInfo *error) {
    NSLog(@"Page 0 item 0: %@", paginatedResult.items[0].data);
    [paginatedResult next:^(ARTPaginatedResult<ARTMessage *> *nextPage, ARTErrorInfo *error) {
        NSLog(@"Page 1 item 1: %@", nextPage.items[1].data);
        NSLog(@"Last page?: %d", nextPage.isLast());
    }];
}];
channel.history { paginatedResult, error in
    let paginatedResult = paginatedResult!
    print("Page 0 item 0: \((paginatedResult.items[0] as! ARTMessage).data)")
    paginatedResult.next { nextPage, error in
        let nextPage = nextPage!
        print("Page 0 item 0: \((nextPage.items[1] as! ARTMessage).data)")
        print("Last page? \(nextPage.isLast())")
    }
}

io.ably.lib.types.Param

Param is a type encapsulating a key/value pair. This type is used frequently in method parameters allowing key/value pairs to be used more flexible, see Channel#history for an example.

Please note that key and value attributes are always strings. If an Integer or other value type is expected, then you must coerce that type into a String.

Members

key
The key value
Type: String
value
The value associated with the key
Type: String

Back to top