Skip to content

Instantly share code, notes, and snippets.

@f3401pal
Created April 8, 2019 14:28
Show Gist options
  • Save f3401pal/f6a2a61fb2b48cce486c3778bf141b57 to your computer and use it in GitHub Desktop.
Save f3401pal/f6a2a61fb2b48cce486c3778bf141b57 to your computer and use it in GitHub Desktop.
RxBroadcastReceiver + DownloadManager example
fun dowloadFile(url: String): Single<Long> {
val expectedId: Long = DownloadManager.Request(Uri.parse(builder.apkUrl)).run { downloadManager.enqueue(this) }
return downloadReceiver.map {
it.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
}.takeWhile {
it == expectedId
}.firstOrError().timeout(3, TimeUnit.MINUTES)
}
class RxBroadcastReceiver(private val context: Context, private val filter: IntentFilter) :
Observable<Intent>() {
override fun subscribeActual(observer: Observer<in Intent>) {
object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
intent?.let {
if (filter.matchAction(it.action)) {
observer.onNext(it)
}
}
}
}.apply {
observer.onSubscribe(ReceiverDisposable(context, this))
context.registerReceiver(this, filter)
}
}
private class ReceiverDisposable(
private val context: Context,
private val receiver: BroadcastReceiver
) : Disposable {
private var isDisposed = false
@Synchronized
override fun isDisposed(): Boolean {
return isDisposed
}
@Synchronized
override fun dispose() {
context.unregisterReceiver(receiver)
isDisposed = true
}
}
}
@f3401pal
Copy link
Author

f3401pal commented Apr 8, 2019

Sometimes, I get an exception on unregisterReceiver when the receiver is already unregistered. Any idea on what causes it? Any suggestions on the disposing logic?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment