Last active
March 23, 2017 19:41
-
-
Save MisterRager/4b1d357a12ea4b0dd70a4792836192ea to your computer and use it in GitHub Desktop.
RxServiceBinding: observe the binding of a service
This file contains hidden or 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
/* | |
* Copyright (c) 2017 PlanGrid, Inc. All rights reserved. | |
*/ | |
package com.plangrid.android.services.rx; | |
import android.app.Service; | |
import android.content.ComponentName; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.ServiceConnection; | |
import android.os.Binder; | |
import android.os.IBinder; | |
import rx.Observable; | |
import rx.Subscriber; | |
public class RxServiceBinding<T extends Binder> implements Observable.OnSubscribe<T> { | |
private final Context context; | |
private final Intent intent; | |
public RxServiceBinding(final Context context, final Intent serviceIntent) { | |
this.context = context; | |
this.intent = serviceIntent; | |
} | |
@Override public void call(Subscriber<? super T> subscriber) { | |
final ServiceConnection callback = new ServiceCallback<T>(subscriber); | |
Observable.<T>create(sub -> { | |
context.bindService(intent, callback, Service.BIND_AUTO_CREATE); | |
}).doOnUnsubscribe(() -> context.unbindService(callback)) | |
.subscribe(subscriber); | |
} | |
private static class ServiceCallback<T extends Binder> implements ServiceConnection { | |
final Subscriber<? super T> subscriber; | |
ServiceCallback(Subscriber<? super T> subscriber) { | |
this.subscriber = subscriber; | |
} | |
@Override public void onServiceConnected(ComponentName name, IBinder service) { | |
if (!subscriber.isUnsubscribed()) { | |
//noinspection unchecked | |
subscriber.onNext((T)service); | |
} | |
} | |
@Override public void onServiceDisconnected(ComponentName name) { | |
subscriber.onCompleted(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment