Skip to content

Instantly share code, notes, and snippets.

@ppicas
Created June 19, 2018 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ppicas/d0af5cda40c5e24aa76527f409a4ea6e to your computer and use it in GitHub Desktop.
Save ppicas/d0af5cda40c5e24aa76527f409a4ea6e to your computer and use it in GitHub Desktop.
class WebSocketPushUpdates(private val context: Context) : PushUpdates {
private val jobSubject = PublishSubject.create<Job>().toSerialized()
override val jobs: Observable<Job> = jobSubject
.doOnSubscribe { bindService() }
.doOnDispose { unbindService() }
private val connection = ServiceConnection()
private var bindingsCount = 0
@Synchronized
private fun bindService() {
bindingsCount++
if (bindingsCount == 1) {
context.bindService(
Intent(context, WebSocketService::class.java),
connection,
Context.BIND_AUTO_CREATE)
}
}
@Synchronized
private fun unbindService() {
bindingsCount--
if (bindingsCount == 0) context.unbindService(connection)
}
inner class ServiceConnection : android.content.ServiceConnection {
var jobUpdatesDisposable: Disposable? = null
override fun onServiceConnected(
name: ComponentName,
service: IBinder
) {
val binder = service as WebSocketService.Binder
jobUpdatesDisposable = binder.jobUpdates
.subscribe { jobSubject.onNext(it) }
}
override fun onServiceDisconnected(name: ComponentName?) {
jobUpdatesDisposable?.dispose()
}
}
}
class WebSocketService : Service() {
private val jobSubject = PublishSubject.create<Job>().toSerialized()
override fun onCreate() {
// Connects to websocket and starts listening events.
// When job updates are received, they are published
// to jobSubject and also used to update JobCache.
}
override fun onDestroy() {
// Disconnects from websocket.
}
override fun onBind(intent: Intent): IBinder? = Binder()
inner class Binder : android.os.Binder() {
val jobUpdates: Observable<Job> = jobSubject
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment