@@ -170,8 +170,8 @@ class PoTokenWebView private constructor(
170170
171171 override fun generatePoToken (identifier : String ): Single <String > =
172172 Single .create { emitter ->
173- addPoTokenEmitter(identifier, emitter)
174- Handler ( Looper .getMainLooper()).post {
173+ runOnMainThread( emitter) {
174+ addPoTokenEmitter(identifier, emitter)
175175 webView.evaluateJavascript(
176176 """ (async function() {
177177 identifier = String.raw`$identifier `
@@ -266,7 +266,7 @@ class PoTokenWebView private constructor(
266266 * to [generatorEmitter].
267267 */
268268 private fun onInitializationErrorCloseAndCancel (error : Throwable ) {
269- Handler ( Looper .getMainLooper()).post {
269+ runOnMainThread(generatorEmitter) {
270270 close()
271271 generatorEmitter.onError(error)
272272 }
@@ -295,15 +295,29 @@ class PoTokenWebView private constructor(
295295 private val TAG = PoTokenWebView ::class .simpleName
296296 private const val GOOGLE_API_KEY = " AIzaSyDyT5W0Jh49F30Pqqtyfdf7pDLFKLJoAnw"
297297 private const val REQUEST_KEY = " O43z0dpjhgX20SCx4KAo"
298- private const val USER_AGENT = " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3"
298+ private const val USER_AGENT = " Mozilla/5.0 (Windows NT 10.0; Win64; x64) " +
299+ " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3"
299300
300301 override fun newPoTokenGenerator (context : Context ): Single <PoTokenGenerator > =
301302 Single .create { emitter ->
302- Handler ( Looper .getMainLooper()).post {
303+ runOnMainThread(emitter) {
303304 val potWv = PoTokenWebView (context, emitter)
304305 potWv.loadHtmlAndObtainBotguard(context)
305306 emitter.setDisposable(potWv.disposables)
306307 }
307308 }
309+
310+ /* *
311+ * Runs [runnable] on the main thread using `Handler(Looper.getMainLooper()).post()`, and
312+ * if the `post` fails emits an error on [emitterIfPostFails].
313+ */
314+ private fun runOnMainThread (
315+ emitterIfPostFails : SingleEmitter <out Any >,
316+ runnable : () -> Unit ,
317+ ) {
318+ if (! Handler (Looper .getMainLooper()).post(runnable)) {
319+ emitterIfPostFails.onError(PoTokenException (" Could not run on main thread" ))
320+ }
321+ }
308322 }
309323}
0 commit comments