Skip to content

Instantly share code, notes, and snippets.

@igoticecream
Last active May 29, 2017 15:54
Show Gist options
  • Save igoticecream/63492e6f368107abc9db3ec7f8f9da3e to your computer and use it in GitHub Desktop.
Save igoticecream/63492e6f368107abc9db3ec7f8f9da3e to your computer and use it in GitHub Desktop.
RxJava example of how to "fix" Observable events going to the main thread
public class ShareConnect implements Single.OnSubscribe<Bundle> {
private final GoogleApiClient client;
private final Scheduler.Worker worker;
private final ShareConnectException error;
public ShareConnect(final Share share) {
this.client = share.getClient();
this.worker = Schedulers.io().createWorker();
this.error = new ShareConnectException("No se ha podido establecer conexión con Google Drive");
}
@Override
public void call(SingleSubscriber<? super Bundle> subscriber) {
if (client.isConnected() || client.isConnecting()) {
log("Error: is connected");
subscriber.onError(error);
}
final OnConnectionFailedListener connectionFailedListener = result -> worker.schedule(() -> {
log("Error: is failed");
subscriber.onError(error);
});
final ConnectionCallbacks connectionListener = new ConnectionCallbacks() {
@Override
public void onConnected(@Nullable Bundle bundle) {
worker.schedule(() -> {
log("Connected");
subscriber.onSuccess(bundle);
});
}
@Override
public void onConnectionSuspended(int i) {
worker.schedule(() -> {
log("Error: is suspended");
subscriber.onError(error);
});
}
};
subscriber.add(worker);
subscriber.add(Subscriptions.create(() -> {
log("Disconnecting");
client.unregisterConnectionCallbacks(connectionListener);
client.unregisterConnectionFailedListener(connectionFailedListener);
client.disconnect();
}));
log("Connecting");
client.registerConnectionFailedListener(connectionFailedListener);
client.registerConnectionCallbacks(connectionListener);
client.connect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment