Struct PubNubClientInstance

Source
pub struct PubNubClientInstance<T, D> { /* private fields */ }
Expand description

PubNub client raw instance.

This struct contains the actual client state. It shouldn’t be used directly. Use PubNubGenericClient or PubNubClient instead.

Implementations§

Source§

impl<T, D> PubNubClientInstance<T, D>

Source

pub fn grant_token( &self, ttl: usize, ) -> GrantTokenRequestBuilder<'_, T, SerdeSerializer, D>

Create grant token permissions request builder. This method is used to generate token with required permissions.

Instance of GrantTokenRequestBuilder returned.

§Example
use pubnub::{
    access::*,
};

let mut pubnub = // PubNubClient
pubnub
    .grant_token(10)
    .resources(&[permissions::channel("test-channel").read().write()])
    .meta(HashMap::from([
         ("role".into(), "administrator".into()),
         ("access-duration".into(), 2800.into()),
         ("ping-interval".into(), 1754.88.into()),
     ]))
    .execute()
    .await?;
Source

pub fn revoke_token<S>(&self, token: S) -> RevokeTokenRequestBuilder<T, D>
where S: Into<String>,

Create grant token request builder.

This method is used to revoke token permissions.

Instance of RevokeTokenRequestBuilder returned.

§Example
use pubnub::{
    access::*,
};

let mut pubnub = // PubNubClient
pubnub
    .revoke_token("p0F2AkF0Gl043r....Dc3BjoERtZXRhoENzaWdYIGOAeTyWGJI")
    .execute()
    .await?;
Source§

impl<T, D> PubNubClientInstance<T, D>
where D: Deserializer,

Source

pub fn publish_message<M>(&self, message: M) -> PublishMessageBuilder<T, M, D>
where M: Serialize,

Create a new publish message builder. This method is used to publish a message to a channel.

Instance of PublishMessageBuilder is returned.

§Example

let mut pubnub = // PubNubClient

pubnub.publish_message("Hello, world!")
   .channel("my_channel")
   .execute()
   .await?;
Source§

impl<T, D> PubNubClientInstance<T, D>
where T: Transport + Send + 'static, D: Deserializer + Send + 'static,

Source

pub fn status_stream(&self) -> DataStream<ConnectionStatus>

Stream used to notify connection state change events.

Source

pub fn clone_empty(&self) -> Self

Creates a clone of the PubNubClientInstance with an empty event dispatcher.

Empty clones have the same client state but an empty list of real-time event listeners, which makes it possible to attach listeners specific to the context. When the cloned client set goes out of scope, all associated listeners will be invalidated and released.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
// ...
// We need to pass client into other component which would like to
// have own listeners to handle real-time events.
let empty_pubnub_client = pubnub.clone_empty();
// self.other_component(empty_pubnub_client);    
§Returns

A new instance of the subscription object with an empty event dispatcher.

Source§

impl<T, D> PubNubClientInstance<T, D>
where T: Transport + Send + 'static, D: Deserializer + Send + 'static,

Source

pub fn subscription<N>( &self, parameters: SubscriptionParams<'_, N>, ) -> SubscriptionSet<T, D>
where N: Into<String> + Clone,

Creates multiplexed subscriptions.

§Arguments
§Returns

The created SubscriptionSet object.

§Example
use futures::StreamExt;
use pubnub::{
    subscribe::{
        EventEmitter, {EventSubscriber, SubscriptionParams},
    },
    Keyset, PubNubClient, PubNubClientBuilder,
};

let pubnub = // PubNubClient
let subscription = pubnub.subscription(SubscriptionParams {
    channels: Some(&["my_channel_1", "my_channel_2", "my_channel_3"]),
    channel_groups: None,
    options: None
});
// Message stream for handling real-time `Message` events.
let stream = subscription.messages_stream();
Source

pub fn disconnect(&self)

Stop receiving real-time updates.

Stop receiving real-time updates for previously subscribed channels and groups by temporarily disconnecting from the PubNub network.

use futures::StreamExt;
use pubnub::{
    subscribe::{
        EventEmitter, {EventSubscriber, SubscriptionParams, Update},
    },
    Keyset, PubNubClient, PubNubClientBuilder,
};

pubnub.disconnect();
Source

pub fn reconnect(&self, cursor: Option<SubscriptionCursor>)

Resume real-time updates receiving.

Restore real-time updates receive from previously subscribed channels and groups by restoring connection to the PubNub network.

use futures::StreamExt;
use pubnub::{
    subscribe::{
        EventEmitter, {EventSubscriber, SubscriptionParams, Update},
    },
    Keyset, PubNubClient, PubNubClientBuilder,
};

pubnub.reconnect(None);
Source

pub fn unsubscribe_all(&self)

Unsubscribes from all real-time events.

Stop any actions for receiving real-time events processing for all created Subscription and SubscriptionSet.

Source§

impl<T, D> PubNubClientInstance<T, D>

Source

pub fn subscribe_raw(&self) -> RawSubscriptionBuilder<T, D>

Create subscription listener.

Listeners configure [PubNubClient] to receive real-time updates for specified list of channels and groups.

use futures::StreamExt;
use pubnub::{
    subscribe::{
        EventEmitter, {EventSubscriber, SubscriptionParams, Update},
    },
    Keyset, PubNubClient, PubNubClientBuilder,
};

# #[tokio::main]
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
#   let pubnub = PubNubClientBuilder::with_reqwest_transport()
#      .with_keyset(Keyset {
#          subscribe_key: "demo",
#          publish_key: Some("demo"),
#          secret_key: None,
#      })
#      .with_user_id("user_id")
#      .build()?;
pubnub
    .subscribe_raw()
    .channels(["hello".into(), "world".into()].to_vec())
    .execute()?
    .stream()
    .for_each(|update| async move {
          println!("Received update: {:?}", update);
    })
    .await;
# Ok(())
# }

For more examples see our examples directory.

Instance of [SubscriptionBuilder] returned. [PubNubClient]: crate::PubNubClient

Source

pub fn set_filter_expression<S>(&self, expression: S)
where S: Into<String>,

Update real-time events filtering expression.

§Arguments
  • expression - A String representing the filter expression.
Source

pub fn get_filter_expression<S>(&self) -> Option<String>

Get real-time events filtering expression.

§Returns

Current real-time events filtering expression.

Source§

impl<T, D> PubNubClientInstance<T, D>

Source

pub fn heartbeat(&self) -> HeartbeatRequestBuilder<T, D>

Create a heartbeat request builder.

This method is used to announce the presence of user_id on the provided list of channels and/or groups.

Instance of [HeartbeatRequestsBuilder] returned.

§Example
use pubnub::presence::*;

#[tokio::main]
let mut pubnub = // PubNubClient
pubnub
    .heartbeat()
    .channels(["lobby".into(), "announce".into()])
    .channel_groups(["area-51".into()])
    .state(HashMap::<String, Vec<u8>>::from(
        [(
            String::from("lobby"),
            HashMap::from([("is_admin".to_string(), false)]).serialize()?
        )]
    ))
    .execute()
    .await?;
Source

pub fn leave(&self) -> LeaveRequestBuilder<T, D>

Create a leave request builder.

This method is used to announce leave of user_id on the provided list of channels and/or groups and update state associated with user_id on channels.

Instance of [LeaveRequestBuilder] returned.

§Example
use pubnub::presence::*;

#[tokio::main]
let mut pubnub = // PubNubClient
pubnub
    .leave()
    .channels(["lobby".into(), "announce".into()])
    .channel_groups(["area-51".into()])
    .execute()
    .await?;
Source

pub fn set_presence_state<S>(&self, state: S) -> SetStateRequestBuilder<T, D>
where T: 'static, D: 'static, S: Serialize,

Create a set state request builder.

This method is used to update state associated with user_id on channels and channels registered with channel groups.

Instance of SetStateRequestBuilder returned.

§Example
use pubnub::presence::*;

#[tokio::main]
let mut pubnub = // PubNubClient
pubnub
    .set_presence_state(HashMap::<String, bool>::from(
         [(String::from("is_admin"), false)]
     ))
    .channels(["lobby".into(), "announce".into()])
    .channel_groups(["area-51".into()])
    .execute()
    .await?;
Source

pub fn set_presence_state_with_heartbeat<S>( &self, state: HashMap<String, S>, ) -> HeartbeatRequestBuilder<T, D>
where S: Serialize,

Create a heartbeat request builder.

This method is used to update state associated with user_id on channels using heartbeat operation endpoint. State with heartbeat can be set only for channels.

Instance of [HeartbeatRequestsBuilder] returned.

§Example
use pubnub::presence::*;

#[tokio::main]
let mut pubnub = // PubNubClient
pubnub
    .set_presence_state_with_heartbeat(HashMap::from([
         ("lobby".to_string(), HashMap::from([("key".to_string(), "value".to_string())])),
         ("announce".to_string(), HashMap::from([("key".to_string(), "value".to_string())])),
    ]))
    .channels(["lobby".into(), "announce".into()])
    .channel_groups(["area-51".into()])
    .execute()
    .await?;
Source

pub fn get_presence_state(&self) -> GetStateRequestBuilder<T, D>

Create a get state request builder.

This method is used to get state associated with user_id on channels and channels registered with channel groups.

Instance of [GetStateRequestBuilder] returned.

§Example
use pubnub::presence::*;

#[tokio::main]
let mut pubnub = // PubNubClient
pubnub
    .get_presence_state()
    .channels(["lobby".into(), "announce".into()])
    .channel_groups(["area-51".into()])
    .execute()
    .await?;
Source

pub fn here_now(&self) -> HereNowRequestBuilder<T, D>

Create a here now request builder.

This method is used to get information about current occupancy of channels and channel groups.

Instance of [HereNowRequestBuilder] returned.

§Example
use pubnub::presence::*;

let mut pubnub = // PubNubClient
let response = pubnub.here_now()
        .channels(["lobby".into()])
        .include_state(true)
        .include_user_id(true)
        .execute()
        .await?;

println!("All channels data: {:?}", response);
Source

pub fn where_now(&self) -> WhereNowRequestBuilder<T, D>

Create a where now request builder.

This method is used to get information about channels where user_id is currently present.

Instance of [WhereNowRequestBuilder] returned.

§Example
use pubnub::presence::*;

let mut pubnub = // PubNubClient
let response = pubnub.where_now().user_id("user_id").execute().await?;

println!("User channels: {:?}", response);
Source§

impl<T, D> PubNubClientInstance<T, D>

Source

pub fn channel<S>(&self, name: S) -> Channel<T, D>
where S: Into<String>,

Creates a new channel with the specified name.

§Arguments
  • name - The name of the channel as a string.
§Returns

Returns a Channel which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let channel = pubnub.channel("my_channel");
Source

pub fn channels<S>(&self, names: &[S]) -> Vec<Channel<T, D>>
where S: Into<String> + Clone,

Creates a list of channels with the specified names.

§Arguments
  • names - A list of names for the channels as a string.
§Returns

Returns a list of Channel which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let channels = pubnub.channels(&["my_channel_1", "my_channel_2"]);
Source

pub fn channel_group<S>(&self, name: S) -> ChannelGroup<T, D>
where S: Into<String>,

Creates a new channel group with the specified name.

§Arguments
  • name - The name of the channel group as a string.
§Returns

Returns a ChannelGroup which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let channel_group = pubnub.channel_group("my_group");
Source

pub fn channel_groups<S>(&self, names: &[S]) -> Vec<ChannelGroup<T, D>>
where S: Into<String> + Clone,

Creates a list of channel groups with the specified names.

§Arguments
  • name - A list of names for the channel groups as a string.
§Returns

Returns a list of ChannelGroup which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let channel_groups = pubnub.channel_groups(&["my_group_1", "my_group_2"]);
Source

pub fn channel_metadata<S>(&self, id: S) -> ChannelMetadata<T, D>
where S: Into<String>,

Creates a new channel metadata object with the specified identifier.

§Arguments
  • id - The identifier of the channel metadata object as a string.
§Returns

Returns a ChannelMetadata which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let channel_metadata = pubnub.channel_metadata("channel_meta");
Source

pub fn channels_metadata<S>(&self, ids: &[S]) -> Vec<ChannelMetadata<T, D>>
where S: Into<String> + Clone,

Creates a list of channel metadata objects with the specified identifiers.

§Arguments
  • id - A list of identifiers for the channel metadata objects as a string.
§Returns

Returns a list of ChannelMetadata which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let channels_metadata = pubnub.channels_metadata(
    &["channel_meta_1", "channel_meta_2"]
);
Source

pub fn user_metadata<S>(&self, id: S) -> UserMetadata<T, D>
where S: Into<String>,

Creates a new user metadata object with the specified identifier.

§Arguments
  • id - The identifier of the user metadata object as a string.
§Returns

Returns a UserMetadata which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let user_metadata = pubnub.user_metadata("user_meta");
Source

pub fn users_metadata<S>(&self, ids: &[S]) -> Vec<UserMetadata<T, D>>
where S: Into<String> + Clone,

Creates a list of user metadata objects with the specified identifier.

§Arguments
  • id - A list of identifiers for the user metadata objects as a string.
§Returns

Returns a list of UserMetadata which can be used with the PubNub API.

§Example
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
let users_metadata = pubnub.users_metadata(&["user_meta_1", "user_meta_2"]);
Source

pub fn set_token<S>(&self, access_token: S)
where S: Into<String>,

Update currently used authentication token.

§Examples
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let token = "<auth token from grant_token>";
let pubnub = // PubNubClient
pubnub.set_token(token);
// Now client has access to all endpoints for which `token` has
// permissions.
Source

pub fn get_token(&self) -> Option<String>

Retrieve currently used authentication token.

§Examples
use pubnub::{PubNubClient, PubNubClientBuilder, Keyset};

let pubnub = // PubNubClient
println!("Current authentication token: {:?}", pubnub.get_token());
// Now client has access to all endpoints for which `token` has
// permissions.
Source§

impl<T, D> PubNubClientInstance<T, D>
where T: Transport + Send + Sync + 'static, D: Deserializer + Send + Sync + 'static,

Source

pub fn terminate(&self)

Terminates the subscription and presence managers if the corresponding features are enabled.

Trait Implementations§

Source§

impl<T, D> Clone for PubNubClientInstance<T, D>

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug, D: Debug> Debug for PubNubClientInstance<T, D>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T, D> Deref for PubNubClientInstance<T, D>

Source§

type Target = PubNubClientRef<T, D>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<T, D> DerefMut for PubNubClientInstance<T, D>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<T, D> EventEmitter for PubNubClientInstance<T, D>

Source§

fn messages_stream(&self) -> DataStream<Message>

Stream used to notify regular messages.
Source§

fn signals_stream(&self) -> DataStream<Message>

Stream used to notify signals.
Source§

fn message_actions_stream(&self) -> DataStream<MessageAction>

Stream used to notify message action updates.
Source§

fn files_stream(&self) -> DataStream<File>

Stream used to notify about file receive.
Source§

fn app_context_stream(&self) -> DataStream<AppContext>

Stream used to notify about App Context (Channel and User) updates.
Source§

fn presence_stream(&self) -> DataStream<Presence>

Stream used to notify about subscribers’ presence updates.
Source§

fn stream(&self) -> DataStream<Update>

Generic stream used to notify all updates mentioned above.

Auto Trait Implementations§

§

impl<T, D> Freeze for PubNubClientInstance<T, D>

§

impl<T, D> !RefUnwindSafe for PubNubClientInstance<T, D>

§

impl<T, D> Send for PubNubClientInstance<T, D>
where T: Sync + Send, D: Sync + Send,

§

impl<T, D> Sync for PubNubClientInstance<T, D>
where T: Sync + Send, D: Sync + Send,

§

impl<T, D> Unpin for PubNubClientInstance<T, D>

§

impl<T, D> !UnwindSafe for PubNubClientInstance<T, D>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more