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

Types

The Ably client library defines both data types and option types. Data types are used to represent object such as messages; Option types are used in method arguments.

Where client libraries support both Realtime and REST APIs, the types are shared between both clients.

All types are always classes or their respective equivalent for each language implementation. Options on the other hand, may often support both typed option classes or more flexible key value objects such as a Hash or plain Javascript object.

If you are interested in finding out more about the exact types and options definitions in each language, we recommend you download our open source libraries and review the code.

Data types

io.ably.lib.types.AblyExceptionAbly::Exceptions::BaseAblyExceptionIO.Ably.AblyException

An AblyException is an exception encapsulating error information containing an Ably-specific error code and generic status code, where applicable.

PropertiesMembersAttributes

errorInfoErrorInfo
@ErrorInfo corresponding to this exception, where applicable
Type: ErrorInfo

A BaseAblyExceptionan AblyException is an exception encapsulating error information containing an Ably-specific error code and generic status code, where applicable.

PropertiesMembersAttributesAttributes

codeCode
Ably error code (see ably-common/protocol/errors.json)
Type: Integer
statusCodestatus_codeStatusCode
HTTP Status Code corresponding to this error, where applicable
Type: Integer
messageMessage
Additional message information, where available
Type: String

DeviceDetailsAbly::Models::DeviceDetails

An DeviceDetails is a type encapsulating attributes of a device registered for push notifications.

PropertiesMembersAttributes

id
unique identifier for the device generated by the device itself
Type: Strinf
clientIdclient_id
optional trusted client identifier for the device
Type: String
formFactorform_factor
form factor of the push device. Must be one of phone, tablet, desktop, tv, watch, car or embedded
Type: String
metadata
optional metadata object for this device. The metadata for a device may only be set by clients with push-admin privileges and will be used more extensively in future with smart notifications
Type: ObjectHash
platform
platform of the push device. Must be one of ios, android or browser
Type: String
updateTokenupdate_token
a token that can be used by typically a mobile device to authenticate with Ably later and update an existing device registration (for example, for updating a GCM or FCM registration token)
Type: String
push.recipient
push recipient details for this device. See the REST API push publish documentation for more details
Type: ObjectHash
push.state
the current state of the push device being either Active, Failing or Failed
Type: String
push.errorReasonpush.error_reason
when the device’s state is failing or failed, this attribute contains the reason for the most recent failure
Type: ErrorInfo

ErrorInfoARTErrorInfoio.ably.lib.types.ErrorInfoAbly::Models::ErrorInfoIO.Ably.ErrorInfo

An ErrorInfo is a type encapsulating error information containing an Ably-specific error code and generic status code.

PropertiesMembersAttributes

codeCode
Ably error code (see ably-common/protocol/errors.json)
Type: Integer
statusCodestatus_codeStatusCode
HTTP Status Code corresponding to this error, where applicable
Type: Integer
messageMessage
Additional message information, where available
Type: String

MessageARTMessageio.ably.lib.types.MessageAbly::Models::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

Presence actionARTPresenceActionio.ably.lib.types.PresenceMessage.ActionAbly::Models::PresenceMessage::ACTIONIO.Ably.PresenceAction

Presence action is a String with a value matching any of the Realtime Presence states & events.

var PresenceActions = [
  'absent', // (reserved for internal use)
  'present',
  'enter',
  'leave',
  'update'
]

io.ably.lib.types.PresenceMessage.Action is an enum representing all the Realtime Presence states & events.

public enum Action {
  ABSENT,  // 0 (reserved for internal use)
  PRESENT, // 1
  ENTER,   // 2
  LEAVE,   // 3
  UPDATE   // 4
}

IO.Ably.PresenceAction is an enum representing all the Realtime Presence states & events.

public enum Action {
  Absent,  // 0 (reserved for internal use)
  Present, // 1
  Enter,   // 2
  Leave,   // 3
  Update   // 4
}

PresenceAction is an enum-like class representing all the Realtime Presence states & events.

class PresenceAction(object):
  ABSENT = 0    # (reserved for internal use)
  PRESENT = 1
  ENTER = 2
  LEAVE = 3
  UPDATE = 4

PresenceMessage Action is one of the class constants representing all the Realtime Presence states & events.

namespace Ably\Models;
class PresenceMessages {
  const ABSENT  = 0; /* (reserved for internal use) */
  const PRESENT = 1;
  const ENTER   = 2;
  const LEAVE   = 3;
  const UPDATE  = 4;
}

Example usage

if ($presenceMessage->action == Ably\Models\PresenceMesage::ENTER) {
  /* do something */
}

Ably::Models::PresenceMessage::ACTION is an enum-like value representing all the Realtime Presence states & events. ACTION can be represented interchangeably as either symbols or constants.

Symbol states

:absent  # => 0 (reserved for internal use)
:present # => 1
:enter   # => 2
:leave   # => 3
:update  # => 4

Constant states

PresenceMessage::ACTION.Absent  # => 0 (internal use)
PresenceMessage::ACTION.Present # => 1
PresenceMessage::ACTION.Enter   # => 2
PresenceMessage::ACTION.Leave   # => 3
PresenceMessage::ACTION.Update  # => 4

Example usage

# Example with symbols
presence.on(:attached) { ... }

# Example with constants
presence.on(Ably::Models::PresenceMessage::ACTION.Enter) { ... }

# Interchangeable
Ably::Models::PresenceMessage::ACTION.Enter == :enter # => true

ARTPresenceAction is an enum representing all the Realtime Presence states & events.

typedef NS_ENUM(NSUInteger, ARTPresenceAction) {
    ARTPresenceAbsent,
    ARTPresencePresent,
    ARTPresenceEnter,
    ARTPresenceLeave,
    ARTPresenceUpdate
};
enum ARTPresenceAction : UInt {
  case Absent
  case Present
  case Enter
  case Leave
  case Update
}

PresenceMessageARTPresenceMessageio.ably.lib.types.PresenceMessageAbly::Models::PresenceMessageIO.Ably.PresenceMessage

A PresenceMessage represents an individual presence update that is sent to or received from Ably.

PropertiesMembersAttributes

action
the event signified by a PresenceMessage. See PresenceMessage.action
Type: enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
Action
the event signified by a PresenceMessage. See PresenceMessage.action
Type: enum { Absent, Present, Enter, Leave, Update }
action
the event signified by a PresenceMessage. See Presence action
Type: int enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
action
the event signified by a PresenceMessage. See PresenceAction
Type: int enum { ABSENT, PRESENT, ENTER, LEAVE, UPDATE }
action
the event signified by a PresenceMessage. See PresenceMessage::ACTION
Type: enum { :absent, :present, :enter, :leave, :update }
action
the event signified by a PresenceMessage. See PresenceMessage::ACTION
Type: const PresenceMessage::ABSENT,PRESENT,ENTER,LEAVE,UPDATE
action
the event signified by a PresenceMessage. See PresenceMessage.action
Type: ARTPresenceAction
data
The presence update payload, if provided
Type: String, ByteArray, JSONObject, JSONArray
Data
The presence update payload, if provided
Type: String, byte[], plain C# object that can be converted to Json
data
The presence update payload, if provided
Type: String, StringBuffer, JSON Object
data
The presence update payload, if provided
Type: String, Binary (ASCII-8BIT String), Hash, Array
data
The presence update payload, if provided
Type: String, Bytearray, Dict, List
data
The message payload, if provided
Type: String, NSData, Dictionary, Array
data
The message payload, if provided
Type: NSString *, NSData *, NSDictionary *, NSArray *
data
The message payload, if provided
Type: String, Binary String, Associative Array, Array
idId
Unique ID assigned by Ably to this presence update
Type: String
clientIdclient_idClientId
The client ID of the publisher of this presence update
Type: String
connectionIdconnection_idConnectionId
The connection ID of the publisher of this presence update
Type: String
timestampTimestamp
Timestamp when the presence update was received by Ably, as milliseconds since the epoch.
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
encodingEncoding
This will typically be empty as all presence updates 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

PresenceMessage constructors

PresenceMessage.fromEncoded

PresenceMessage.fromEncoded(Object encodedPresMsg, ChannelOptions channelOptions?) → PresenceMessage

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

Parameters

encodedPresMsg
a PresenceMessage-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 PresenceMessage object

PresenceMessage.fromEncodedArray

PresenceMessage.fromEncodedArray(Object[] encodedPresMsgs, ChannelOptions channelOptions?) → PresenceMessage[]

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

Parameters

encodedPresMsgs
an array of PresenceMessage-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 PresenceMessage objects

PaginatedResultARTPaginatedResultio.ably.lib.types.PaginatedResultAbly::Models::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())")
    }
}

HttpPaginatedResponse

An HttpPaginatedResponse is a superset of PaginatedResult, which is a type that represents a page of results plus metadata indicating the relative queries available to it. HttpPaginatedResponse additionally carries information about the response to an HTTP request. It is used when making custom HTTP requests.

PropertiesMembersAttributesAttributes

itemsItems
contains a page of results (for example an Array of Message or PresenceMessage objects for a channel history request).
Type: Array<>Type: List<>
statusCodestatus_codeStatusCode
the HTTP status code of the response
Type: Number
successSuccess
whether that HTTP status code indicates success (equivalent to 200 <= statusCode < 300)
Type: Boolean
headersHeaders
the response’s headers
Type: Object

Methods

firstFirst

first(callback(ErrorInfo err, HttpPaginatedResponse resultPage))HttpPaginatedResponse firstHttpPaginatedResponse first()HttpPaginatedResponse first()Task<HttpPaginatedResponse> FirstAsync()HttpPaginatedResponse first()first(callback: (ARTHttpPaginatedResponse?, ARTErrorInfo?) → Void)

Returns a new HttpPaginatedResponse for the first page of results. When using the Realtime library, the first method returns a Deferrable and yields an HttpPaginatedResponse.The method is asynchronous and returns a Task which needs to be awaited to get the @HttpPaginatedResponse":/realtime/types#http-paginated-response.

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, HttpPaginatedResponse resultPage))HttpPaginatedResponse nextHttpPaginatedResponse next()HttpPaginatedResponse next()Task<HttpPaginatedResponse > NextAsync()HttpPaginatedResponse next()next(callback: (ARTHttpPaginatedResponse?, ARTErrorInfo?) → Void)

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

Example

The HttpPaginatedResponse interface is a superset of PaginatedResult, see the PaginatedResult example

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

PushChannelSubscriptionAbly::Models::PushChannelSubscription

An PushChannelSubscription is a type encapsulating the subscription of a device or group of devices sharing a client identifier to a channel in order to receive push notifications.

PropertiesMembersAttributes

channel
the channel that this push notification subscription is associated with
Type: String
deviceIddevice_id
the device with this identifier is linked to this channel subscription. When present, clientIdclient_id is never present
Type: String
clientIdclient_id
devices with this client identifier are included in this channel subscription. When present, deviceIddevice_id is never present
Type: String

PushChannelSubscription constructors

PushChannelSubscription.forDevicePushChannelSubscription.for_device

PushChannelSubscription.forDevice(String channel, String deviceId) → PushChannelSubscriptionPushChannelSubscription.for_device(String channel, String device_id) → PushChannelSubscription

A static factory method to create a PushChannelSubscription object for a channel and single device.

Parameters

channel
channel name linked to this push channel subscription
Type: String
deviceIddevice_id
the device with this identifier will be linked with this push channel subscription
Type: String

Returns

A PushChannelSubscription object

PushChannelSubscription.forClientPushChannelSubscription.for_client

PushChannelSubscription.forDevice(String channel, String clientId) → PushChannelSubscriptionPushChannelSubscription.for_device(String channel, String client_id) → PushChannelSubscription

A static factory method to create a PushChannelSubscription object for a channel and group of devices sharing a client identifier.

Parameters

channel
channel name linked to this push channel subscription
Type: String
clientIdclient_id
devices with this client identifier are included in the new push channel subscription
Type: String

Returns

A PushChannelSubscription object

TokenDetailsARTTokenDetailsio.ably.lib.types.TokenDetailsAbly::Models::TokenDetailsIO.Ably.TokenDetails

TokenDetails is a type providing details of the token string and its associated metadata.

PropertiesMembersAttributes

tokenToken
The token itself. A typical token string may appear like {{TOKEN}}
Type: String
expiresExpires
The time (in milliseconds since the epoch)The time at which this token expires
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
issuedIssued
The time (in milliseconds since the epoch)The time at which this token was issued
Type: IntegerLong IntegerDateTimeOffsetTimeNSDate
capabilityCapability
The capability associated with this token. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities
Type: StringCapability
clientIdclient_idClientId
The client ID, if any, bound to this token. If a client ID is included, then the token authenticates its bearer as that client ID, and the token may only be used to perform operations on behalf of that client ID. The client is then considered to be an identified client
Type: String

Methods

expired?
True when the token has expired
Type: Boolean

Methods

is_expired()
True when the token has expired
Type: Boolean

Methods

IsValidToken()
True if the token has not expired
Type: Boolean

TokenDetails constructors

TokenDetails.fromJsonTokenDetails.from_json

TokenDetails.fromJson(String json) → TokenDetailsTokenDetails.from_json(String json) → TokenDetails

TokenDetails.fromJson(Object json) → TokenDetailsTokenDetails.from_json(Object json) → TokenDetails

A static factory method to create a TokenDetails from a deserialized TokenDetails-like object or a JSON stringified TokenDetails. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenDetails object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenDetails, Ably ensures that all fields are consistently serialized and deserialized across platforms.

Parameters

json
a TokenDetails-like deserialized object or JSON stringified TokenDetails.
Type: Object, String

Returns

A TokenDetails object

TokenRequestARTTokenRequestio.ably.lib.types.TokenRequestAbly::Models::TokenRequestIO.Ably.TokenRequest

TokenRequest is a type containing parameters for a token request. Tokens are requested using Auth#requestTokenAuth#request_token

PropertiesMembersAttributes

keyNamekey_nameKeyName
The key name of the key against which this request is made. The key name is public, whereas the key secret is private
Type: String
ttlTtl
Requested time to live for the token in millisecondsin secondsas a TimeSpan. If the token request is successful, the TTL of the returned token will be less than or equal to this value depending on application settings and the attributes of the issuing key.
Type: IntegerTimeSpanNSTimeInterval
timestampTimestamp
The timestamp of this request in milliseconds
Type: IntegerLong IntegerTimeDateTimeOffsetNSDate
capabilityCapability
Capability of the token. If the token request is successful, the capability of the returned token will be the intersection of this capability with the capability of the issuing key. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilities
Type: String
clientIdclient_idClientId
The client ID to associate with this token. When provided, the token may only be used to perform operations on behalf of that client ID
Type: String
nonceNonce
An opaque nonce string of at least 16 characters
Type: String
macMac
The Message Authentication Code for this request
Type: String

TokenRequest constructors

TokenRequest.fromJsonTokenRequest.from_json

TokenRequest.fromJson(String json) → TokenRequestTokenRequest.from_json(String json) → TokenRequest

TokenRequest.fromJson(Object json) → TokenRequestTokenRequest.from_json(Object json) → TokenRequest

A static factory method to create a TokenRequest from a deserialized TokenRequest-like object or a JSON stringified TokenRequest. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenRequest object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenRequest, Ably ensures that all fields are consistently serialized and deserialized across platforms.

Parameters

json
a TokenRequest-like deserialized object or JSON stringified TokenRequest.
Type: Object, String

Returns

A TokenRequest object

Stats objectARTStatsio.ably.lib.types.StatsAbly::Models::StatsIO.Ably.Stats

A Stats object represents a application statistic for the specified interval and time period. Ably aggregates statistics globally for all accounts and applications, and makes these available both through our statistics API as well as your application dashboard.

Please note that most attributes of the Stats type below contain references to further stats types. This documentation is not exhaustive for all stats types, and as such, links to the stats types below will take you to the Ruby library stats documentation which contains exhaustive stats documentation. Ruby and Python however uses under_score case instead of the default camelCase in most languages, so please bear that in mind.

PropertiesMembersAttributesKeyword arguments

allAll
aggregate count of both inbound and outbound message stats
Type: MessageTypes
apiRequestsapi_requestsApiRequests
breakdown of API requests received via the Ably REST API
Type: RequestCount
channelsChannels
breakdown of channel related stats such as min, mean and peak channels
Type: ResourceCount
connectionsConnections
breakdown of connection related stats such as min, mean and peak channels for TLS and non-TLS connections
Type: ConnectionTypes
inboundInbound
statistics such as count and data for all inbound messages received over REST and Realtime connection, broken down by normal channel messages or presence messages
Type: MessageTraffic
interval_granularityIntervalGranularity
A GRANULARITY constantvalueEnum representing the granularity (interval) of this statistic such as :minute, :hour, :day, :month'minute', 'hour', 'day', 'month'Minute, Hour, Day, Month.
Type: Stats::GRANULARITYStringStatsIntervalGranularity enum
intervalIdinterval_idIntervalId
the interval ID provides both the time from which the interval starts as well as the length of time that this statistic covers i.e. the period of time which the stats are aggregated for. For example, an interval ID value of “2016-03-01:10:02” represents a single minute interval for the UTC time presented in the string. However, an interval ID of “2016-03” represents a month interval for the entire month of March 2016 based on UTC time.
Type: String
interval_timeIntervalTime
A TimeDateTimeDateTimeOffset object representing the start of the interval
Type: TimeDateTimeDateTimeOffset
outboundOutbound
statistics such as count and data for all outbound messages retrieved via REST history requests, received over Realtime connections, or pushed with WebHooks, broken down by normal channel messages or presence messages
Type: MessageTraffic
persistedPersisted
messages persisted and later retrieved via the history API
Type: MessageTypes
tokenRequeststoken_requestsTokenRequests
breakdown of Token requests received via the Ably REST API.
Type: RequestCount

ARTStatsGranularity

ARTStatsGranularity is an enum specifying the granularity of a ARTStats interval.

typedef NS_ENUM(NSUInteger, ARTStatsGranularity) {
    ARTStatsGranularityMinute,
    ARTStatsGranularityHour,
    ARTStatsGranularityDay,
    ARTStatsGranularityMonth
};
enum ARTStatsGranularity : UInt {
    case Minute
    case Hour
    case Day
    case Month
}

StatsIntervalGranularity is an enum specifying the granularity of a Stats interval.

public enum StatsGranularity
{
    Minute,
    Hour,
    Day,
    Month
}

Other types

AuthOptions ObjectARTAuthOptionsAuthOptions Hashio.ably.lib.rest.Auth.AuthOptionsIO.Ably.AuthOptions

AuthOptions is a plain Javascript object and is used when making authentication requests. If passed in, an authOptions object will be used instead of (as opposed to supplementing or being merged with) the default values given when the library was instanced. The following attributes are supported:

AuthOptions is a Hash object and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced. The following key symbol values can be added to the Hash:

AuthOptions is a Dict and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced. The following key symbol values can be added to the Dict:

AuthOptions is an Associative Array and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced. The following named keys and values can be added to the Associative Array:

ARTAuthOptions is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instanced.

PropertiesMembersAttributesAttributes

authCallbackAuthCallbackauth_callback:auth_callback
A functionfunction with the form function(tokenParams, callback(err, tokenOrTokenRequest))TokenCallback instancecallable (eg a lambda)proc / lambda (called synchronously in REST and Realtime but does not block EventMachine in the latter) which is called when a new token is required. The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object. See an authentication callback example or our authentication documentation for details of the token request format and associated API calls.
Type: CallableTokenCallbackProcFunc<TokenParams, Task<TokenDetails>>
authUrlAuthUrl:auth_urlauth_url
A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format). For example, this can be used by a client to obtain signed token requests from an application server.
Type: StringUriNSURL
authMethodAuthMethod:auth_methodauth_method
GET:get The HTTP verb to use for the request, either GET:get or POST:post
Type: StringSymbolHttpMethod
authHeadersAuthHeaders:auth_headersauth_headers
A set of key value pair headers to be added to any request made to the authUrlAuthUrl. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials will be set on the xhr request.
Type: ObjectHashAssociative ArrayParam[]Dictionary<string, string>NSDictionary<String *, String *>[String, String]/Dictionary<String, String>
authParamsAuthParams:auth_paramsauth_params
A set of key value pair params to be added to any request made to the authUrlAuthUrl. When the authMethodAuthMethod is GET, query params are added to the URL, whereas when authMethodAuthMethod is POST, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response.
Type: ObjectHashAssociative ArrayParam[]Dictionary<string, string>NSArray<NSURLQueryItem *>[NSURLQueryItem]/Array<NSURLQueryItem>
keyKey:keykey
Optionally the API key to use can be specified as a full key string; if not, the API key passed into ClientOptions when instancing the Realtime or REST library is used
Type: String
queryTimeQueryTime:query_timequery_time
false If true, the library will query the Ably servers for the current time instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed token requests, so this option is useful for library instances on auth servers if the server clock is insufficiently accurate. The server is queried only once per client library instance, and used to calculate and store the offset from the local clock.
Type: Boolean
tokenToken:tokentoken
An authenticated token string that is most commonly obtained from the tokenToken property of a TokenDetails component of a token request response. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: String
tokenDetailsTokenDetails:token_detailstoken_details
An authenticated TokenDetails object that is most commonly obtained from of a token request response. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: TokenDetails

ClientOptions ObjectARTClientOptionsClientOptions Hashio.ably.types.ClientOptionsIO.Ably.ClientOptions

ClientOptions is a plain Javascript object and is used in the Ably.Realtime constructor’s options argument. The following attributes can be defined on the object:

ClientOptions is a Hash object and is used in the Ably::Realtime constructor’s options argument. The following key symbol values can be added to the Hash:

ClientOptions is a associative array and is used in the Ably\AblyRest constructor’s options argument. The following named keys and values can be added to the associative array:

ARTClientOptions is used in the AblyRealtime constructor’s options argument.

PropertiesMembersAttributesKeyword arguments

keyKey:key
The full key string, as obtained from the application dashboard. Use this option if you wish to use Basic authentication, or wish to be able to issue tokens without needing to defer to a separate entity to sign token requests. Read more about Basic authentication
Type: String
tokenToken:token
An authenticated token string that is most commonly obtained from the tokenToken property of a TokenDetails component of a token request response. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: String
tokenDetailsTokenDetailstoken_details:token_details
An authenticated TokenDetails object that is most commonly obtained from of a token request response. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: TokenDetails
tlsTls:tls
true A boolean value, indicating whether or not a TLS (“SSL”) secure connection should be used. An insecure connection cannot be used with Basic authentication ensuring private keys are compromised in transit. Find out more about TLS
Type: Boolean
clientIdClientIdclient_id:client_id
A client ID, used for identifying this client when publishing messages or for presence purposes. The clientIdclient_idClientId can be any non-empty string. This option is primarily intended to be used in situations where the library is instanced with a key; note that a clientIdclient_idClientId may also be implicit in a token used to instance the library; an error will be raised if a clientIdclient_id specified here conflicts with the clientIdclient_idClientId implicit in the token. Find out more about client identities
Type: String
authCallbackAuthCallbackauth_callback:auth_callback
A functionfunction with the form function(tokenParams, callback(err, tokenOrTokenRequest))TokenCallback instancecallable (eg a lambda)proc / lambda (called synchronously in REST and Realtime but does not block EventMachine in the latter) which is called when a new token is required. The role of the callback is to either generate a signed TokenRequest which may then be submitted automatically by the library to the Ably REST API requestToken; or to provide a valid token in as a TokenDetails object. See an authentication callback example or our authentication documentation for details of the token request format and associated API calls.
Type: CallableTokenCallbackProcFunc<TokenParams, Task<TokenDetails>>
authUrlAuthUrlauth_url:auth_url
A URL that the library may use to obtain a token string (in plain text format), or a signed TokenRequest or TokenDetails (in JSON format). For example, this can be used by a client to obtain signed token requests from an application server.
Type: StringUri
authMethodAuthMethodauth_method:auth_method
GET:get The HTTP verb to use for the request, either GET:get or POST:post
Type: StringSymbolHttpMethod
authHeadersAuthHeadersauth_headers:auth_headers
A set of key value pair headers to be added to any request made to the authUrlAuthUrl. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials will be set on the xhr request.
Type: ObjectDictHashAssociative ArrayParam []Dictionary<string, string>
authParamsAuthParamsauth_params:auth_params
A set of key value pair params to be added to any request made to the authUrlAuthUrl. When the authMethodAuthMethod is GET, query params are added to the URL, whereas when authMethodAuthMethod is POST, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response.
Type: ObjectDictHashAssociative ArrayParam []Dictionary<string, string>
useTokenAuthUseTokenAuthuse_token_auth:use_token_auth
false When true, forces Token authentication to be used by the library. Please note that if a client_idclientId is not specified in the ClientOptions or TokenParams, then the token issued will be anonymous.
Type: Boolean
log
Parameters to control the log output of the library. The supplied value must be an object that may contain one or both of the following entries:

  • level: a number controlling the verbosity of the output. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).

  • handler: a function to handle each line of log output. If handler is not specified, console.log is used.


Note that the log level and log handler have global scope in the library and will thus not act independently between library instances when multiple library instances exist concurrently.
Type: Object
transports
An optional array of transports to use, in descending order of preference. In the browser environment the available transports are: web_socket, xhr, jsonp.The transports available in the Node.js client library are: web_socket, xhr, comet.
Type: String []
logLevel
5 A number controlling the verbosity of the output from 2 (maximum, verbose) to 6 (errors only). A special value of 99 will silence all logging. Note that the logLevel is a static variable in the library and will thus not act independently between library instances when multiple library instances exist concurrently.
Type: Integer
logHandler
System.out PrintStream A LogHandler interface can be specified to handle each line of log output. If logHandler is not specified, System.out is used. Note that the logHandler is a static variable in the library and will thus not act independently between library instances when multiple library instances exist concurrently.
Type: PrintStream

To set the log level and custom logger sink when using the .Net library, configure the static IO.Ably.Logger class or specify the ClientOptions:

LogLevel
Error This is an enum controlling the verbosity of the output from Debug (maximum) to Error (errors only). A special value of None will silence all logging. Note that the LogLevel is a static variable in the library and will thus not act independently between library instances.
Type: Enum
LoggerSink
IO.Ably.DefaultLoggerSink The default ILoggerSink outputs messages to the debug console. This property allows the user to pipe the log messages to their own logging infrastructure.
logLevel
ARTLogLevelWarn An enum controlling the verbosity of the output from ARTLogLevelVerbose to ARTLogLevelNone. A special value of 99 will silence all logging.
Type: ARTLogLevel
logHandler
A ARTLog object can be specified to handle each line of log output. If logHandler is not specified, a default ARTLog instance is used.
Type: ARTLog *
:log_level
:error Log level for the standard Logger that outputs to STDOUT. Can be set to :fatal, :error, :warn, :info, :debug or :none. Alternatively a Logger severity constant can be specified.
Type: Symbol, Logger::SEVERITY
:logger
STDOUT Logger A Ruby Logger compatible object to handle each line of log output. If logger is not specified, STDOUT is used.
Type: Ruby @Logger
logLevel
Log::WARNING A number controlling the verbosity of the output from 1 (minimum, errors only) to 4 (most verbose);
Type: Integer
logHandler
console.log A function to handle each line of log output. If handler is not specified, console.log is used. Note that the log level and log handler have global scope in the library and will therefore not act independently between library instances when multiple library instances exist concurrently.
Type: Function
useBinaryProtocolUseBinaryProtocoluse_binary_protocol:use_binary_protocol
false If set to true, will enable the binary protocol (MessagePack) if it is supported. It’s disabled by default on browsers for performance considerations (browsers are optimized for decoding JSON)true If set to false, will forcibly disable the binary protocol (MessagePack). The binary protocol is used by default unless it is not supportedNote: The binary protocol is currently not supported in Swiftin Objective-Cin PHP. Find out more about the benefits of binary encoding
Type: Boolean
queueMessagesQueueMessages:queue_messages
true If false, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior allows applications to submit messages immediately upon instancing the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing under those conditions
Type: Boolean
echoMessagesEchoMessages:echo_messages
true If false, prevents messages originating from this connection being echoed back on the same connection
Type: Boolean
autoConnectAutoConnect:auto_connect
true By default as soon as the client library is instanced it will connect to Ably. You can optionally set this to false and explicitly connect to Ably when require using the connect method
Type: Boolean
recover
This option allows a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See connection state recovery for further information
Type: String, Callable
closeOnUnload
false When true, the client library will automatically send a close request to Ably whenever the window beforeunload event fires. By enabling this option, the close request sent to Ably ensures the connection state will not be retained and all channels associated with the channel will be detached. This is commonly used by developers who want presence leave events to fire immediately i.e. if a user navigates to another page or closes their browser, then enabling this option will result in the presence member leaving immediately. Without this option or an explicit call to the close method of the Connection object, Ably expects that the abruptly disconnected connection could later be recovered and therefore does not immediately remove the user from presence. Instead, to avoid “twitchy” presence behavior an abruptly disconnected client is removed from channels in which they are present after 15 seconds, and the connection state is retained for two minutes
Type: Boolean
recoverRecover:recover
This option allows a connection to inherit the state of a previous connection that may have existed under a different instance of the library by providing that connection’s recoveryKeyrecovery_key. This might typically be used by clients of an app to ensure connection state can be preserved following a reload. See connection state recovery for further information and example code
Type: String
queryTimeQueryTime:query_time
false If true, the library will query the Ably servers for the current time instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed token requests, so this option is useful for library instances on auth servers if the server clock is insufficiently accurate. The server is queried only once per client library instance, and used to calculate and store the offset from the local clock.
Type: Boolean
defaultTokenParamsDefaultTokenParams:default_token_params
When a TokenParams object is provided, it will override the client library defaults when issuing new tokens or token requests
Type: TokenParams
disconnectedRetryTimeoutDisconnectedRetryTimeout:disconnected_retry_timeout
15,000ms15s When the connection enters the DISCONNECTED state, after this delay in millisecondsin secondsas a NSTimeInterval, if the state is still DISCONNECTED, the client library will attempt to reconnect automatically
Type: IntegerNSTimeInterval
suspendedRetryTimeoutSuspendedRetryTimoeut:suspended_retry_timeout
30,000ms30s When the connection enters the SUSPENDED state, after this delay in millisecondsin secondsas a NSTimeInterval, if the state is still SUSPENDED, the client library will attempt to reconnect automatically
Type: IntegerNSTimeInterval

ChannelOptions ObjectARTChannelOptionsChannelOptions Hashio.ably.lib.types.ChannelOptionsIO.Ably.Rest.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.

ChannelStateARTRealtimeChannelStateChannel::STATE Enumio.ably.lib.realtime.ChannelState EnumIO.Ably.Realtime.ChannelState Enum

ChannelState is a String with a value matching any of the Realtime Channel states.

var ChannelStates = [
  'initialized',
  'attaching',
  'attached',
  'detaching',
  'detached',
  'failed',
  'suspended'
]

io.ably.lib.realtime.ChannelState is an enum representing all the Realtime Channel states.

public enum ChannelState {
  initialized,  // 0
  attaching,    // 1
  attached,     // 2
  detaching,    // 3
  detached,     // 4
  failed        // 5
}

IO.Ably.Realtime.ChannelState is an enum representing all the Realtime Channel states.

public enum ChannelState
{
    Initialized = 0,
    Attaching = 1,
    Attached = 2,
    Detaching= 3,
    Detached = 4,
    Failed = 5
};

Ably::Realtime::Channel::STATE is an enum-like value representing all the Realtime Channel states. STATE can be represented interchangeably as either symbols or constants.

Symbol states

:initialized # => 0
:attaching # =>   1
:attached # =>    2
:detaching # =>   3
:detached # =>    4
:failed # =>      5

Constant states

Channel::STATE.Initialized # => 0
Channel::STATE.Attaching # =>   1
Channel::STATE.Attached # =>    2
Channel::STATE.Detaching # =>   3
Channel::STATE.Detached # =>    4
Channel::STATE.Failed # =>      5

Example usage

# Example with symbols
channel.on(:attached) { ... }

# Example with constants
channel.on(Ably::Realtime::Channel::STATE.Attached) { ... }

# Interchangeable
Ably::Realtime::Channel::STATE.Attached == :attached # => true

ARTRealtimeChannelState is an enum representing all the Realtime Channel states.

typedef NS_ENUM(NSUInteger, ARTRealtimeChannelState) {
    ARTRealtimeChannelInitialized,
    ARTRealtimeChannelAttaching,
    ARTRealtimeChannelAttached,
    ARTRealtimeChannelDetaching,
    ARTRealtimeChannelDetached,
    ARTRealtimeChannelFailed
};
public enum ARTRealtimeChannelState : UInt {
    case Initialized
    case Attaching
    case Attached
    case Detaching
    case Detached
    case Failed
}

ChannelEventARTChannelEventChannel::EVENT Enumio.ably.lib.realtime.ChannelEvent EnumIO.Ably.Realtime.ChannelEvent Enum

ChannelEvent is a String that can be emitted as an event on the Channel object; either a ChannelState or an update event.

var ChannelEvents = [
  'initialized',
  'attaching',
  'attached',
  'detaching',
  'detached',
  'failed',
  'suspended',
  'update'
]

io.ably.lib.realtime.ChannelEvent is an enum representing all the events that can be emitted be the Channel; either a ChannelState or an update event.

public enum ChannelEvent {
  initialized,  // 0
  attaching,    // 1
  attached,     // 2
  detaching,    // 3
  detached,     // 4
  failed        // 5
  update        // 6
}

IO.Ably.Realtime.ChannelEvent is an enum representing all the events that can be emitted be the Channel; either a ChannelState or an Update event.

public enum ChannelEvent
{
    Initialized = 0,
    Attaching = 1,
    Attached = 2,
    Detaching= 3,
    Detached = 4,
    Failed = 5,
    Update = 6
};

Ably::Realtime::Channel::EVENT is an enum-like value representing all the events that can be emitted be the Channel; either a ChannelState or an :update event. EVENT can be represented interchangeably as either symbols or constants.

Symbol states

:initialized # => 0
:attaching # =>   1
:attached # =>    2
:detaching # =>   3
:detached # =>    4
:failed # =>      5
:update # =>      6

Constant states

Channel::EVENT.Initialized # => 0
Channel::EVENT.Attaching # =>   1
Channel::EVENT.Attached # =>    2
Channel::EVENT.Detaching # =>   3
Channel::EVENT.Detached # =>    4
Channel::EVENT.Failed # =>      5
Channel::EVENT.Update # =>      6

ARTChannelEvent is the enum emitted as the event in ARTRealtimeChannel.on; either a ChannelState or an Update event.

typedef NS_ENUM(NSUInteger, ARTChannelEvent) {
    ARTChannelEventInitialized,
    ARTChannelEventAttaching,
    ARTChannelEventAttached,
    ARTChannelEventDetaching,
    ARTChannelEventDetached,
    ARTChannelEventFailed,
    ARTChannelEventUpdate
};
enum ARTChannelEvent : UInt {
    case Initialized
    case Attaching
    case Attached
    case Detaching
    case Detached
    case Failed
    case Update
}

ChannelStateChange ObjectARTRealtimeChannelStateChangeChannelStateChangeio.ably.lib.realtime.ConnectionStateListener.ChannelStateChangeIO.Ably.Realtime.ChannelStateChange

A Ably::Models::ChannelStateChangeChannelStateChangeARTRealtimeChannelStateChange is a type encapsulating state change information emitted by the Channel object. See Channel#on to register a listener for one or more events.

Attributes

currentCurrent
the new current state
Type: ChannelStateChannel::STATE@
previousPrevious
the previous state. (for the update event, this will be equal to the current state)
Type: ChannelStateChannel::STATE@
eventEvent
the event that triggered this state change
Type: ChannelEventChannel::EVENT@
reasonReason
an ErrorInfo containing any information relating to the transition
Type: ErrorInfo
resumedResumed
a boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info.
Type: Boolean

io.ably.lib.realtime.ChannelStateListener

A io.ably.lib.realtime.ChannelStateListener is an interface allowing a client to be notified of channel state changes for a Channel

public interface ChannelStateListener {
  // Called when the channel state changes
  public void onChannelStateChanged(ChannelStateChange stateChange, ErrorInfo reason);
}

CipherParamsARTCipherParamsCipherParams Hashio.ably.lib.util.Crypto.CipherParamsIO.Ably.CipherParams

A CipherParams contains configuration options for a channel cipher, including algorithm, mode, key length and key. Ably client libraries currently support AES with CBC, PKCS#7 with a default key length of 256 bits. All implementations also support AES128.

Individual client libraries may support either instancing a CipherParams directly, using Crypto.getDefaultParams()Crypto.GetDefaultParams()Crypto.get_default_params(), or generating one automatically when initializing a channel, as in this example.

PropertiesMembersAttributes

keyKey:key
A binary (byte[]ArrayBuffer or WordArrayBufferbyte arrayNSData) containing the secret key used for encryption and decryption
algorithm:algorithmAlgorithm
AES The name of the algorithm in the default system provider, or the lower-cased version of it; eg “aes” or “AES”
Type: String
key_length:key_lengthkeyLengthKeyLength
256 The key length in bits of the cipher, either 128 or 256
Type: Integer
mode:modeMode
CBC The cipher mode
Type: StringCipherMode
keySpec
A KeySpec for the cipher key
Type: SecretKeySpec

io.ably.lib.realtime.CompletionListener

A io.ably.lib.realtime.CompletionListener is an interface allowing a client to be notified of the outcome of an asynchronous operation.

public interface CompletionListener {
  // Called when the associated operation completes successfully,
  public void onSuccess();

  // Called when the associated operation completes with an error.
  public void onError(ErrorInfo reason);
}

ConnectionStateARTRealtimeConnectionStateConnection::STATEio.ably.lib.realtime.ConnectionStateIO.Ably.Realtime.ConnectionState

ConnectionState is a String with a value matching any of the Realtime Connection states.

var ConnectionStates = [
  'initialized',
  'connecting',
  'connected',
  'disconnected',
  'suspended',
  'closing',
  'closed',
  'failed'
]

io.ably.lib.realtime.ConnectionState is an enum representing all the Realtime Connection states.

public enum ConnectionState {
  initialized,   // 0
  connecting,    // 1
  connected,     // 2
  disconnected,  // 3
  suspended,     // 4
  closing,       // 5
  closed,        // 6
  failed         // 7
}

IO.Ably.Realtime.ConnectionState is an enum representing all the Realtime Connection states.

public enum ConnectionState
{
    Initialized,    //0
    Connecting,     //1
    Connected,      //2
    Disconnected,   //3
    Suspended,      //4
    Closing,        //5
    Closed,         //6
    Failed          //7
};

Ably::Realtime::Connection::STATE is an enum-like value representing all the Realtime Connection states. STATE can be represented interchangeably as either symbols or constants.

Symbol states

:initialized # =>  0
:connecting # =>   1
:connected # =>    2
:disconnected # => 3
:suspended # =>    4
:closing # =>      5
:closed # =>       6
:failed # =>       7

Constant states

Connection::STATE.Initialized # =>  0
Connection::STATE.Connecting # =>   1
Connection::STATE.Connected # =>    2
Connection::STATE.Disconnected # => 3
Connection::STATE.Suspended # =>    4
Connection::STATE.Closing # =>      5
Connection::STATE.Closed # =>       6
Connection::STATE.Failed # =>       7

Example usage

# Example with symbols
client.connection.on(:connected) { ... }

# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }

# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true

ARTRealtimeConnectionState is an enum representing all the Realtime Connection states.

typedef NS_ENUM(NSUInteger, ARTRealtimeConnectionState) {
    ARTRealtimeInitialized,
    ARTRealtimeConnecting,
    ARTRealtimeConnected,
    ARTRealtimeDisconnected,
    ARTRealtimeSuspended,
    ARTRealtimeClosing,
    ARTRealtimeClosed,
    ARTRealtimeFailed
};
public enum ARTRealtimeConnectionState : UInt {
    case Initialized
    case Connecting
    case Connected
    case Disconnected
    case Suspended
    case Closing
    case Closed
    case Failed
}

ConnectionEventARTRealtimeConnectionEventConnection::EVENT Enumio.ably.lib.realtime.ConnectionEvent EnumIO.Ably.Realtime.ConnectionEvent Enum

ConnectionEvent is a String that can be emitted as an event on the Connection object; either a Realtime Connection state or an update event.

var ConnectionEvents = [
  'initialized',
  'connecting',
  'connected',
  'disconnected',
  'suspended',
  'closing',
  'closed',
  'failed',
  'update'
]

io.ably.lib.realtime.ConnectionEvent is an enum representing all the events that can be emitted be the Connection; either a Realtime Connection state or an update event.

public enum ConnectionEvent {
  initialized,   // 0
  connecting,    // 1
  connected,     // 2
  disconnected,  // 3
  suspended,     // 4
  closing,       // 5
  closed,        // 6
  failed,        // 7
  update         // 8
}

IO.Ably.Realtime.ConnectionEvent is an enum representing all the events that can be emitted be the Connection; either a Realtime Connection state or an Update event.

public enum ConnectionState
{
    Initialized,    //0
    Connecting,     //1
    Connected,      //2
    Disconnected,   //3
    Suspended,      //4
    Closing,        //5
    Closed,         //6
    Failed,         //7
    update          //8
};

Ably::Realtime::Connection::EVENT is an enum-like value representing all the events that can be emitted be the Connection; either a Realtime Connection state or an :update event. EVENT can be represented interchangeably as either symbols or constants.

Symbol states

:initialized # =>  0
:connecting # =>   1
:connected # =>    2
:disconnected # => 3
:suspended # =>    4
:closing # =>      5
:closed # =>       6
:failed # =>       7
:update # =>       8

Constant states

Connection::EVENT.Initialized # =>  0
Connection::EVENT.Connecting # =>   1
Connection::EVENT.Connected # =>    2
Connection::EVENT.Disconnected # => 3
Connection::EVENT.Suspended # =>    4
Connection::EVENT.Closing # =>      5
Connection::EVENT.Closed # =>       6
Connection::EVENT.Failed # =>       7
Connection::EVENT.Update # =>       8

Example usage

# Example with symbols
client.connection.on(:connected) { ... }

# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }

# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true

ARTRealtimeConnectionEvent is an enum representing all the events that can be emitted be the Connection; either a Realtime Connection state or an Update event.

typedef NS_ENUM(NSUInteger, ARTRealtimeConnectionEvent) {
    ARTRealtimeConnectionEventInitialized,
    ARTRealtimeConnectionEventConnecting,
    ARTRealtimeConnectionEventConnected,
    ARTRealtimeConnectionEventDisconnected,
    ARTRealtimeConnectionEventSuspended,
    ARTRealtimeConnectionEventClosing,
    ARTRealtimeConnectionEventClosed,
    ARTRealtimeConnectionEventFailed,
    ARTRealtimeConnectionEventUpdate
};
public enum ARTRealtimeConnectionEvent : UInt {
    case Initialized
    case Connecting
    case Connected
    case Disconnected
    case Suspended
    case Closing
    case Closed
    case Failed
    case Update
}

io.ably.lib.realtime.ConnectionStateListener

A io.ably.lib.realtime.ConnectionStateListener is an interface allowing a client to be notified of connection state change. See Connection#on to register a listener for one or more events.

public interface ConnectionStateListener {
  // Called when the connection state changes
  public void onConnectionStateChanged(ConnectionStateListener.ConnectionStateChange state);
}

ConnectionStateChange ObjectARTConnectionStateChangeConnectionStateChangeio.ably.lib.realtime.ConnectionStateListener.ConnectionStateChangeIO.Ably.Realtime.ConnectionStateChange

A io.ably.lib.realtime.ConnectionStateListener.ConnectionStateChangeAbly::Models::ConnectionStateChangeARTConnectionStateChangeIO.Ably.Realtime.ConnectionStateChangeConnectionStateChange is a type encapsulating state change information emitted by the Connection object. See Connection#on to register a listener for one or more events.

PropertiesMembersAttributes

currentCurrent
the new state
Type: State StringConnection::STATEConnectionState
previousPrevious
the previous state. (for the update event, this will be equal to the current state)
Type: State StringConnection::STATEConnectionState
eventEvent
the event that triggered this state change
Type: ConnectionEventConnection::EVENT@
reasonReason
an ErrorInfo containing any information relating to the transition
Type: ErrorInfo
retryInretry_inRetryIn
Duration upon which the library will retry a connection where applicable, as millisecondssecondsa Timespan
Type: IntegerTimespanLong Integer

IO.Ably.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>

io.ably.lib.realtime.Channel.MessageListener

A io.ably.lib.realtime.Channel.MessageListener is an interface allowing a client to be notified when messages are received on a channel using a channel subscription.

public interface MessageListener {
  // Called when one or more messages are received
  public void onMessage(Message message);
}

LastConnectionDetails

A LastConnectionDetails object provides details on the last connection in a browser environment persisted when the window beforeunload fired. This object is provided to the callback specified in the recover attribute of ClientOptions. The callback in turn instructs the client library whether the connection should be recovered or not. See connection state recovery for more information.

Please note that as sessionStorage is used to persist the LastConnectionDetails between page reloads, it is only available for pages in the same origin and top-level browsing context.

Properties

recoveryKey
An opaque string obtained from the recoveryKey attribute of the Connection object before the page was unloaded. This property is used by the library to recover the connection
Type: String
disconnectedAt
the time at which the previous library was abruptly disconnected before the page was unloaded. This is represented as milliseconds since epoch
Type: Integer
location
a clone of location object of the previous page’s document object before the page was unloaded. A common use case for this attribute is to ensure that the previous page URL is the same as the current URL before allowing the connection to be recovered. For example, you may want the connection to be recovered only for page reloads, but not when a user navigates to a different page
Type: String
clientId
the clientId of the client’s Auth object before the page was unloaded. A common use case for this attribute is to ensure that the current logged in user’s clientId matches the previous connection’s clientId before allowing the connection to be recovered. Ably prohibits changing a clientId for an existing connection, so any mismatch in clientId during a recover will result in the connection moving to the failed state
Type: String

io.ably.lib.realtime.Presence.PresenceListener

A io.ably.lib.realtime.Channel.MessageListener is an interface allowing a client to be notified when messages are received on a channel using a channel subscription.

public interface MessageListener {
  // Called when one or more messages are received
  public void onMessage(Message message);
}

Ably::Util::SafeDeferrable

The SafeDeferrable class provides an EventMachine compatible Deferrable.

A SafeDeferrable ensures that any exceptions in callbacks provided by developers will not break the client library and stop further execution of code.

Methods

callback

callback(&block)

Specify a block to be executed if and when the Deferrable object receives a status of :succeeded. See the EventMachine callback documentation

errback

errback(&block)

Specify a block to be executed if and when the Deferrable object receives a status of :failed. See the EventMachine errback documentation

fail

fail(*args)

Mark the Deferrable as failed and trigger all callbacks. See the EventMachine fail documentation

succeed

succeed(*args)

Mark the Deferrable as succeeded and trigger all callbacks. See the EventMachine succeed documentation

IO.Ably.StatsRequestParams

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>

TokenParams ObjectARTTokenParamsTokenParams Hashio.ably.lib.rest.Auth.TokenParamsIO.Ably.TokenParams

TokenParams is a plain Javascript object and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following attributes can be defined on the object:

TokenParams is a Hash object and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following key symbol values can be added to the Hash:

TokenParams is a Dict and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following keys-value pairs can be added to the Dict:

TokenParams is an Associative Array and is used in the parameters of token authentication requests, corresponding to the desired attributes of the token. The following named keys and values can be added to the Associative Array:

TokenParams is used in the parameters of token authentication requests, corresponding to the desired attributes of the token.

ARTTokenParams is used in the parameters of token authentication requests, corresponding to the desired attributes of the token.

PropertiesMembersAttributesAttributes

capabilityCapability:capability
JSON stringified capability of the token. If the token request is successful, the capability of the returned token will be the intersection of this capability with the capability of the issuing key. Find our more about how to use capabilities to manage access privileges for clients. Type: StringCapability
clientIdClientIdclient_id:client_id
A client ID, used for identifying this client when publishing messages or for presence purposes. The clientIdclient_idClientId can be any non-empty string. This option is primarily intended to be used in situations where the library is instanced with a key; note that a clientIdclient_idClientId may also be implicit in a token used to instance the library; an error will be raised if a clientIdclient_idClientId specified here conflicts with the clientIdclient_idClientId implicit in the token. Find out more about client identities
Type: String
nonceNonce:nonce
An optional opaque nonce string of at least 16 characters to ensure uniqueness of this request. Any subsequent request using the same nonce will be rejected.
Type: String
timestamptimestamp:timestamp
The timestamp (in milliseconds since the epoch)The timestamp of this request. timestamp, in conjunction with the nonce, is used to prevent token requests from being replayed.
Type: IntegerLong IntegerTimeNSDateDateTimeOffset
ttlTtl:ttl
1 hour Requested time to live for the token being created in millisecondsin secondsas a NSTimeIntervalas a TimeSpan. When omitted, the Ably REST API default of 60 minutes is applied by Ably
Type: Integer (milliseconds)Integer (seconds)NSTimeIntervalLong IntegerTimeSpan

Back to top