Live Service

The Kinvey Live Service enables an event-driven way to receive data live on your device.

In the past, when an entity has been updated in a Kinvey collection, a user would have to perform a Find operation to retrieve the latest data. Using the Kinvey Live Service, updates from the Kinvey backend can instead be pushed down to the device when an entity has been updated.

In addition to the live updating of entities on your device, the Kinvey Live Service can also enable quick and secure real-time communication between users, in a publish/subscribe pattern. When a user sends a message to another user, that user will receive the message live on their device.

Kinvey Live Service is currently in Early Adopter phase! We are continuously making additions and improvements to this feature, based on early adopter feedback. Please refer to this guide for the latest updates, and check out the Current Limitations to see what will be coming soon. If you have any questions or feedback, please contact us at support@kinvey.com.

Enabling Live Service

The Kinvey Live Service must be enabled on a per-app basis before it can be used. To do so, open the Kinvey Console and select your app. Then, navigate to the app settings page, where you will find a menu item for Live Service. Click this menu item.

Live Service Console Tab

In the Live Service settings page (shown below), simply toggle the switch to On to enable the service for your app. This will allow all environments within this app to use the Live Service.

Live Service Console Enable

If at any point you would like to disable Live Service for your app, navigate back to this page and toggle the switch to the Off position.

Register For Live Service

Once enabled, you can configure your client-side app to start using the Live Service. To do so, the app must first register an active user. Once you have a user logged into your app, use the following code to register:

User activeUser = Kinvey.SharedClient.ActiveUser;
try 
{
    await activeUser.RegisterRealtimeAsync();    
} 
catch (KinveyException e)
{
    // handle registration errors    
}

Similarly, to stop using the Live Service, unregister the user as shown below.

User activeUser = Kinvey.SharedClient.ActiveUser;
try 
{
    await activeUser.UnregisterRealtimeAsync();    
} 
catch (KinveyException e)
{
    // handle unregistration errors
}

Collection Subscription

An app can subscribe to one or more Kinvey collections. Subscribing to a collection allows the app to receive a live feed of all entities that are created or updated in the collection.

On the DataStore corresponding to a collection, call Subscribe with a delegate of type KinveyDataStoreDelegate. This delegate exposes three actions that will be triggered when messages or errors arrive from the Live Service.

  • OnNext: receives entities added or updated in this collection
  • OnError: receives any errors that occur during communication with Live Service
  • OnStatus: receives informational messages regarding Live Service

Status updates arrive on the OnStatus method as a KinveyRealtimeStatus object. These objects indicate informational events such as connecting or disconnecting to Live Service.

Whereas the OnStatus callback gets called with informational updates, the OnError method gets invoked when an exception has occurred with the Kinvey Live Service. These error include events such as not being able to subscribe to Live Service, or permission errors when attempting to use Live Service.

DataStore<Book> books = DataStore<Book>.collection("book");

await books.Subscribe(new KinveyDataStoreDelegate<Book>
{
     OnNext = (result) => {
         // handle new real-time messages
     },
     OnStatus = (status) => {
         // handle subscription status changes
     },
     OnError = (err) => {
         // handle errors
     }
});

To stop receiving live updates from a collection, simply Unsubscribe.

await books.Unsubscribe();

User-to-user communication

Certain app use cases require that users or devices communicate directly with one another, allowing for faster communication than is possible using collection subscriptions. The user-to-user communication feature of the Kinvey Live Service offers one way of approaching these types of use cases. Continue reading to understand this feature, and to see if it can help you when building your solution.

User-to-user communication is accomplished using a Stream object. You can think of a Stream as an object that controls the communication of a specific type of message using the Kinvey Live Service.

A Stream object is mapped to a stream that you create on the backend (using the Console) and has a number of responsibilities:

  • Encapsulate a specific type of message to be passed among users.
  • Grant access rights to specific users of the stream, controlling who can send and receive messages.
  • Provide APIs for communicating messages. The API you use will depend on how you model your user-to-user communication.

Each of these responsibilities, along with creating a stream in the Console, is discussed in greater detail below.

Stream Message Type and Creation

When you create a Stream, you associate a user-defined class with it. This class defines the schema of the messages that are sent and received using this Stream, representing a specific type of message. For example, say that we are modeling song recommendation messages, represented as a SongRecommendation class:

// Live Service Stream Type
using Newtonsoft.Json;

public class SongRecommendation
{
    [JsonProperty("song_name")]
    public string Name { get; set; }

    [JsonProperty("song_artist")]
    public string Artist { get; set; }

    [JsonProperty("rating")]
    public int Rating { get; set; }

    public SongRecommendation(string name, string artist, string rating)
    {
        Name = name;
        Artist = artist;
        Rating = rating;
    }
}

To create a stream that will be used to pass messages of the SongRecommendation type, we begin by creating a stream on the backend, through the Console. Navigate to the environment dashboard for an app that has Live Service enabled, and click the Live Service menu item.

Live Service Console Menu Item

Selecting this will display the Live Service environment settings page, which has sections for both Collection Subscription and User-to-User Communication.

Live Service Console View

Click on the Add a Stream button to create a stream, and then follow the instructions and fill in the necessary information.

Live Service Create Stream

Click Save to finish creating the SongRecommendation stream.

Live Service Create Stream

Now that we created a stream on the backend, we can create a matching Stream object in our client app, and connect the two.

// Create stream object corresponding to "SongRecommendation" stream via the backend
var stream = new Stream<SongRecommendation>("SongRecommendation");

After this step, we have a stream object for sending and receiving SongRecommendation messages. The next step would be to decide how you want to model your user-to-user communication.

Communication Models

There are two primary ways to model user-to-user communication: Directed Communication or Feed Communication. You will typically choose one of these, depending on the use case you are trying to solve. We detail these communication models below. For each model, we discuss the pattern represented by it, explain how to set appropriate access rights on a Stream to support that model, and highlight the API methods you will use.

Directed Communication

The first, and perhaps most straightforward approach to modeling user-to-user communication, is Directed Communication. In this approach, each user can create a message and send it to another user, who is listening for incoming messages. The diagram below illustrates an example of this involving three users, and the communication relationships among them.

User-to-user Directed Communication

In this example, we want John to be able to send directed messages to Paul, and we also want George to send directed messages to Paul. Likewise, we want Paul to listen to any messages sent to him. We also want Paul to send messages to George. Lastly, we want George to listen to messages sent to him. The key in implementing this behavior is to grant the correct access on the Stream to the appropriate users.

Granting Access to Streams

By default, users do not have access to send or receive messages on a stream. Regardless of whether the communication model is Directed or Feed, users must be granted the appropriate access rights to the stream before they can communicate.

Granting access on a stream is done on a per-user basis. This means that we specify who can send messages to a user, as well as specify who can receive messages that are sent to a user. To illustrate this, let us first grant the correct access rights for Paul on this stream. According to the diagram, we want both John and George to be able to send messages to Paul, and we want Paul to be able to receive messages sent to him.

To do this, we create and update a StreamAccessControlList object, which allows us to specify (by their user ID) users who can send messages to Paul (we call these publishers). Additionally, it allows us to specify users who can receive messages sent to Paul (we call these subscribers). In the case of the example above, only Paul will be able to subscribe to messages sent to him. After creating the StreamAccessControlList, we use the GrantStreamAccess method on our stream object to apply these access privileges to Paul.

// Grant stream access for Paul:
//     John and George can send messages to Paul
//     Paul can listen to messages sent to himself

var acl = new StreamAccessControlList();

acl.Publishers.Add(John.Id);
acl.Publishers.Add(George.Id);

acl.Subscribers.Add(Paul.Id);

bool success = await stream.GrantStreamAccess(Paul.Id, acl);

Similarly, we can set up the correct access for George. Paul can send messages to George, and George can listen to messages sent to himself. As emphasized by this last part, remember that since no users can send or receive messages until they are granted the appropriate access, we must grant George access to subscribe to himself.

// Grant stream access for George:
//     Paul can send messages to George
//     George can listen to messages sent to him

var aclGeorge = new StreamAccessControlList();

aclGeorge.Publishers.Add(Paul.Id);

aclGeorge.Subscribers.Add(George.Id);

bool success = await stream.GrantStreamAccess(George.Id, aclGeorge);

Sending Messages and Listening

At this point, the Stream has been properly configured for access. Now the Stream can be used to communicate messages. In the Directed Communication model, the API paradigm used is send/listen. The user that is sending messages specifies the message receiver, and the receiver listens for any messages sent to him.

Referencing the diagram and the SongRecommendation type above, John can send Paul a SongRecommendation message using the Send method:

var songrec = new SongRecommendation("Imagine","John Lennon",100);

await stream.Send(Paul.Id, songrec);

Likewise, Paul can listen to any stream messages that are sent to him using the Listen method:

var streamDelegate = new KinveyStreamDelegate<SongRecommendation>
{
    OnNext = (senderID, message) => {
        // handle receiving new song recommendation
    },
    OnStatus = (status) => {
        // handle status changes
    },
    OnError = (err) => {
        // handle errors
    }
});

await stream.Listen(streamDelegate);

Here you will notice that a handler object is passed into the Listen method. This KinveyStreamDelegate handler is a delegate which will receive the messages that are sent to this user. The KinveyStreamDelegate exposes three actions that will be triggered when messages or errors arrive from the Live Service.

  • OnNext: receives real-time messages of the specified type, and their corresponding sender user ID
  • OnError: receives any errors that occur during communication with the Live Service
  • OnStatus: receives informational messages regarding the Live Service

The KinveyStreamDelegate methods for OnStatus and OnError are similar to those of the KinveyDataStoreDelegate, which are described in the Collection Subscription section.

If at some point in time, Paul wants to stop receiving messages sent to him, he can stop listening to the stream:

await stream.StopListening();

Feed Communication

While Directed Communication allows for communication by explicitly deciding who receives a message, there may be cases where you want a user to send a single message to be read by a number of other users, without explicitly sending the message to each user. This behavior is more intuitively modeled by Feed Communication.

In the Feed Communication model, instead of sending a message to someone specific, a user sends that message to anyone who is listening to him. Other users interested in those messages would then watch, or follow, that user to see those messages.

This is accomplished using a post/follow API paradigm, where a user who is sending a message would post this message, and other users that want to see this message would follow this user.

User-to-user Feed Communication

In the diagram above, both John and Paul post messages to anyone who would listen. George wants to see messages from both John and Paul, so he follows them both. Paul would only like to see messages from John, so he follows only him.

Granting Access to Streams

As with Directed Communication, we need to add the correct access rights to the stream in order to allow for Feed Communication. Since this is a different model, we will grant publish and subscribe access in a different way. In Feed Communication, the only one who should be allowed to publish to a user is that user himself, since he is "posting" the message to anyone following him. The subscribers are all users who want to follow this user. In the case of John, he will be allowed to publish to himself (post messages), while both Paul and George will be allowed to subcribe to John (follow him).

// Grant stream access for John:
//     John can send messages to himself (post)
//     Paul and George can listen to messages sent to John (follow)

var aclForJohn = new StreamAccessControlList();

aclForJohn.Publishers.Add(John.Id);

aclForJohn.Subscribers.Add(Paul.Id);
aclForJohn.Subscribers.Add(George.Id);

bool success = await stream.GrantStreamAccess(John.Id, aclForJohn);

For Paul, he will similarly be able to post to himself, and George can follow him.

// Grant stream access for Paul:
//     Paul can send messages to himself (post)
//     George can listen to messages sent to Paul (follow)

var aclForPaul = new StreamAccessControlList();

aclForPaul.Publishers.Add(Paul.Id);

aclForPaul.Subscribers.Add(George.Id);

bool success = await stream.GrantStreamAccess(Paul.Id, aclForPaul);

And here is where the advantage of Feed Communication for this use case can be seen. As more users want to follow the posts of a specific user, all you have to do is change the access for the posting user to include these new followers. Now, when the new users follow this user, they will see new posts, and the posting user does not have to change anything. The posting user only needs to send a message once, and any user who follows him will receive it.

Posting Messages and Following Users

Now that the appropriate Feed Communication access has been granted, John can Post a new song recommendation to all users who follow him:

var songrec = new SongRecommendation("Strawberry Fields Forever","The Beatles",95);

await stream.Post(songrec);

Paul would Follow John in order to see his song recommendations, using a KinveyStreamDelegate just like with Directed Communication.

var streamDelegate = new KinveyStreamDelegate<SongRecommendation>
{
    OnNext = (senderID, message) => {
        // handle receiving new song recommendation
    },
    OnStatus = (status) => {
        // handle status changes
    },
    OnError = (err) => {
        // handle errors
    }
});

await stream.Follow(John.Id, streamDelegate);

At some point in time, if Paul no longer wants to see John's song recommendations, he can Unfollow John.

await stream.Unfollow(John.Id);

Current Limitations

The Kinvey Live Service feature is currently in its Early Adopter phase, and while we are continuously adding features and fixing issues as we move towards a GA release, there are still limitations and features not yet implemented.

  • Limitations:
    • Message size: Entities that are larger than 32K will not be sent via the Kinvey Live Service.
  • Features not yet implemented:
    • Collection Subscription: Notification of deleted entities.
    • SDK Support: Currently, only the Xamarin, .NET and Swift SDKs support Live Service. Support for other SDKs to completed soon.
    • Collection Subscription: Storing new/updated entities in local storage using collection subscription with DataStoreType.CACHE or DataStoreType.SYNC stores.

Related Samples

Got a question?