Skip to content

Instantly share code, notes, and snippets.

@feresr
Created Aug 26, 2016
Embed
What would you like to do?
/**
* Created by feresr on 8/08/16.
* This use case connects to the PubNub server and informs its listener of incoming messages.
* Usage: Simply setting a listener will start the PunNub subscription. Setting the listener to null will cancel it.
*/
public class InboxUseCase extends UseCase<InboxUseCase.InboxCallbackListener> {
private final static String TAG = InboxUseCase.class.getSimpleName();
private PubNub pubnub;
private Profile profile;
private Handler handler;
@Inject
public InboxUseCase(PubNub pubnub, Profile profile) {
this.pubnub = pubnub;
this.profile = profile;
this.handler = new Handler();
pubnub.addListener(new SubscribeCallback() {
@Override
public void status(PubNub pubnub, PNStatus status) {
Log.e(TAG, "pubnub status: " + status.getCategory().toString());
if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
pubnub.reconnect();
} else if (status.getCategory() == PNStatusCategory.PNTimeoutCategory) {
if (listener.onPubNubTimeout()) {
pubnub.reconnect();
}
} else {
if (status.isError()) {
Log.d(TAG, status.getErrorData().toString());
}
}
}
@Override
public void message(PubNub pubnub, PNMessageResult m) {
try {
Log.d(TAG, "pubnub message: " + m.getMessage().toString());
final Message message = new Gson().fromJson(m.getMessage().toString(), Message.class);
message.setTimeToken(m.getTimetoken());
if (listener != null) {
handler.post(new Runnable() {
@Override
public void run() {
listener.onNewMessageReceived(message);
}
});
}
} catch (final Exception e) {
e.printStackTrace();
if (listener != null) {
handler.post(new Runnable() {
@Override
public void run() {
listener.onErrorReceivingMessage(e.getMessage());
}
});
}
}
}
@Override
public void presence(PubNub pubnub, PNPresenceEventResult presence) {
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment