Skip to content Skip to sidebar Skip to footer

Use Main Thread After Long Network Operation

In my android app I has long network operation. After operation is finished I need to update my ui. So as result long operation need to execute in background thread. Snippet: priva

Solution 1:

You can switch to main thread like with the withContext(Dispatchers.Main) When you fire a coroutine with launch will start on the Dispatchers.Default. The best is to specify it like this:

GlobalScope.launch(Dispatchers.IO) {
            try {
                val executeOperations = OperationFactory.createExecuteTraderOperation(Trader.Operation.CREATE, base, quote)
                val response: Response<Void> = executeOperations.await()
                if (response.isSuccessful) { 
                  withContext(Dispatchers.Main){ //switched to Main thread
                    isShowProgressLiveData.value = false
                    isForwardToTradersLiveData.value = true
                 }
                } else {
                    Debug.w(TAG, "doClickStart_error")
                }
            } catch (e: Throwable) {
                Debug.e(TAG, "doClickStart_network error: $e.message", e)
            }
        }

EDIT: Or you can just use .postValue() instead of .value or .setValue() and forget about withContext().

Solution 2:

You're still in background thread when you try to execute

isShowProgressLiveData.value = false

You can do something like this:

GlobalScope.launch() {
        try {
            val executeOperations = OperationFactory.createExecuteTraderOperation(Trader.Operation.CREATE, base, quote)
            val response: Response<Void> = executeOperations.await()
            if (response.isSuccessful) { 


                YourActivity.runOnUiThread(object:Runnable() {

                overridefunrun() {
                isShowProgressLiveData.value = false
                isForwardToTradersLiveData.value = true
                    }


             }
            } else {
                Debug.w(TAG, "doClickStart_error")
            }
        } catch (e: Throwable) {
            Debug.e(TAG, "doClickStart_network error: $e.message", e)
        }
    }

Post a Comment for "Use Main Thread After Long Network Operation"