Allan Wang
12/21/2018, 12:46 AM// Original
private fun setWebCookie(cookie: String?, callback: (() -> Unit)?) {
with(CookieManager.getInstance()) {
removeAllCookies { _ ->
if (cookie == null) {
callback?.invoke()
return@removeAllCookies
}
L.d { "Setting cookie" }
val cookies = cookie.split(";").map { Pair(it, SingleSubject.create<Boolean>()) }
cookies.forEach { (cookie, callback) -> setCookie(FB_URL_BASE, cookie) { callback.onSuccess(it) } }
Observable.zip<Boolean, Unit>(cookies.map { (_, callback) -> callback.toObservable() }) {}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
callback?.invoke()
L.d { "Cookies set" }
L._d { cookie }
flush()
}
}
}
}
// With suspension
private suspend fun suspendSetWebCookie(cookie: String?) {
cookie ?: return
val manager = CookieManager.getInstance()
manager.removeAllCookies()
cookie.split(":").forEach {
manager.setSingleWebCookie(it)
}
}
private suspend fun CookieManager.removeAllCookies(): Boolean = suspendCoroutine { cont ->
removeAllCookies {
cont.resume(it)
}
}
private suspend fun CookieManager.setSingleWebCookie(cookie: String): Boolean = suspendCoroutine { cont ->
setCookie(FB_URL_BASE, cookie) {
cont.resume(it)
}
}
The use of RX initially was slight overkill, given there’s no thread switching or anything really asynchronous in my logic. I’m going to ignore the error handling for now.gildor
12/22/2018, 2:30 AMsuepend
prefix from setWebCookie.
Also probably would be more idiomatic to convert setWebCookie to extension function of CookieManager, it also good because you do not hide instance of CookieManager and even can test this function with mocked CookieManager instance