Created
August 26, 2016 05:11
-
-
Save feresr/af934546ac6771f05fd671dbce339d2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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