Created
April 8, 2019 14:28
-
-
Save f3401pal/f6a2a61fb2b48cce486c3778bf141b57 to your computer and use it in GitHub Desktop.
RxBroadcastReceiver + DownloadManager example
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
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) | |
} |
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
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 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?