Synchronize threads in Android - android

What is the best way to synchronize threads in this case:
fun doSomething() {
readFromDB.subscribe(object : DisposableMaybeObserver<List<Trip>>()) {
override onSuccess() {
callback.complete()
}
override onFailure() {
callback.complete()
}
}
}
Two threads access this block and run into a race condition.
I need only one thread to read from DB and have that state until the callback completes.
How to lock the other thread from executing this block.
Tried using a lock / synchronized. But, how to unlock from within the onSuccess or onFailure. Does not solve the problem.
In other words, how to wait for the thread to read from DB and get back onSuccess / onFailure, for the 2nd thread to do the same.

You could confine the observation to a single-threaded scheduler. Typically, one would need to run completion code on the main thread thus:
readFromDB
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : DisposableMaybeObserver<List<Trip>>()) {
override onSuccess() {
callback.complete()
}
override onFailure() {
callback.complete()
}
}
If the target thread doesn't matter, you could also use Schedulers.single().

Related

How to use a callback in specific thread in order to wait for it in the main thread?

First question here, I will do my best.
I have a Data class that retrieve a data object with firestore at the creation.
I have done some code to the setters with coroutines. I am not sure of my solution but it is working. However, for the getters, I am struggling to wait the initialisation.
In the initialisation, I have a callback to retrieve the data. The issue that the callback is always called from the main thread, event if I use it in a coroutine in another thread. I check this with:
Log.d("THREAD", "Execution thread1: "+Thread.currentThread().name)
For the setter I use a coroutine in useTask to not block the main thread. And a mutex to block this coroutine until the initialisation in the init is done. Not sure about waitInitialisationSuspend but it is working.
But for the getter, I just want to block the main thread (even if it is bad design, it is a first solution) until the initialisation is done, and resume the getter to retrieve the value.
But I am not enable to block the main thread without also blocking the callback in the initialisation because there are in the same thread.
I have read many documentation about coroutine, scope, runBlocking, thread etc. but everything gets mixed up in my head.
class Story(val id: String) : BaseObservable() {
private val storyRef = StoryHelper.getStoryRef(id)!!
private var isInitialized = false
private val initMutex = Mutex(true)
#get:Bindable
var dbStory: DbStory? = null
init {
storyRef.get().addOnCompleteListener { task ->
if (task.isSuccessful && task.result != null) {
dbStory = snapshot.toObject(DbStory::class.java)!!
if (!isInitialized) {
initMutex.unlock()
isInitialized = true
}
notifyPropertyChanged(BR.dbStory)
}
}
}
fun interface StoryListener {
fun onEvent()
}
private fun useTask(function: (task: Task) -> Unit): Task {
val task = Task()
GlobalScope.launch {
waitInitialisationSuspend()
function(task)
}
return task
}
private suspend fun waitInitialisationSuspend()
{
initMutex.withLock {
// no op wait for unlock mutex
}
}
fun typicalSetFunction(value: String) : Task {
return useTask { task ->
storyRef.update("fieldName", value).addOnSuccessListener {
task.doEvent()
}
}
}
fun typicalGetFunction(): String
{
var result = ""
// want something to wait the callback in the init.
return result
}
}
RunBlocking seems to block the main tread, so I can not use it if the callback still use the main thread.
It is the same problem if I use a while loop in main thread.
#1
runBlocking {
initMutex.withLock {
result = dbStory!!.value
}
}
#2
while (!isInitialized){
}
result = dbStory!!.value
#3
Because maybe the callback in the init is in the main thread also. I have tried to launch this initialisation in a coroutines with a IO dispatcher but without success. The coroutine is well in a different thread but the callback still called in the main thread.
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
scope.launch() {
reference.get().addOnCompleteListener { task ->
In the getter, I have to work with the main thread. The solution is maybe to put the callback execution in another thread but I do not know how to do this. And maybe there is a better solution.
Another solution will be te be able to wait the callback in the main thread without blocking the callback but I have no solution for this.
Any ideas ?
I have loocked for many solutions and the conclusion is, don't do it.
This design is worse than I thougt. Android does not want you to block the main thread even for a short time. Blocking the main thread is blocking all UI and synchronisation mecanism, it is really bad solution.
Even using another thread for the callback (that you can do with an Executor) is, I think, a bad idea here. The good way to wait the end of the task in the callback is to retrieve the task and use:
Tasks.await(initTask)
But it is not allowed in the main thread. Android prevent you to do bad design here.
We should deal with the asynchronous way to manage firebase data base, it is the best way to do that.
I can still use my cache on the data. Here I was waiting to display a dialog with a text I retrieve in firebase. So, I can just display the dialog asynchronously when the text data is retrieved. If the cache is available, it will use it.
Keep also in mind that firebase seems to have some API to use a cache.

Kotlin: lag in coroutine runBlocking

I am using kotlin Coroutines to perform async network operations to avoid NetworkOnMainThreadException.
The problem is the lag that happens when i use runBlocking,that take sometime to complete current thread.
How can i prevent this delay or lag,and allow the async operation to be done without delay
runBlocking {
val job = async (Dispatchers.IO) {
try{
//Network operations are here
}catch(){
}
}
}
By using runBlocking you are blocking the main thread until the coroutine finishes.
The NetworkOnMainThread exception is not thrown because technically the request is done on a background thread, but by making the main thread wait until the background thread is done, this is just as bad!
To fix this you could launch a coroutine, and any code that depends on the network request can be done inside the coroutine. This way code may still be executed on the main thread, but it never blocks.
// put this scope in your activity or fragment so you can cancel it in onDestroy()
val scope = MainScope()
// launch coroutine within scope
scope.launch(Dispachers.Main) {
try {
val result = withContext(Dispachters.IO) {
// do blocking networking on IO thread
""
}
// now back on the main thread and we can use 'result'. But it never blocked!
} catch(e: Exception) {
}
}
If you don't care about the result and just want to run some code on a different thread, this can be simplified to:
GlobalScope.launch(Dispatchers.IO) {
try {
// code on io thread
} catch(e: Exception) {
}
}
Note: if you are using variables or methods from the enclosing class you should still use your own scope so it can be cancelled in time.

Kotlin Coroutines - Are nested coroutines the proper way to handle different threading within one coroutine?

I'm trying out coroutines instead of RxJava on basic network calls for the fist time to see what it's like and running into some issues with lag/threading
In the below code, I'm doing a network call userRepo.Login() and if an exception happens I show an error message and stop the progress animation that I started at the start of the function.
If I leave everything on the CommonPool (or don't add any pool) it crashes saying the animation must be done on a looper thread if an exception happens. In other circumstances I've received errors saying this must be done on the UI thread as well, same problem, different thread requirements.
I can't launch the whole coroutine on the UI thread though, because the login call will block since it's on the UI thread and messes up my animation (which makes sense).
The only way I can see to resolve this, is the launch a new coroutine on the UI thread from within the existing coroutine, which works, but seems weird.
Is this the proper way to do things, or am I missing something?
override fun loginButtonPressed(email: String, password: String) {
view.showSignInProgressAnimation()
launch(CommonPool) {
try {
val user = userRepo.login(email, password)
if (user != null) {
view.launchMainActivity()
}
} catch (exception: AuthException) {
launch(UI) {
view.showErrorMessage(exception.message, exception.code)
view.stopSignInProgressAnimation()
}
}
}
}
You should start from the opposite end: launch a UI-based coroutine, from which you hand off heavy operations to an external pool. The tool of choice is withContext():
override fun loginButtonPressed(email: String, password: String) {
view.showSignInProgressAnimation()
// assuming `this` is a CoroutineScope with dispatcher = Main...
this.launch {
try {
val user = withContext(IO) {
userRepo.login(email, password)
}
if (user != null) {
view.launchMainActivity()
}
} catch (exception: AuthException) {
view.showErrorMessage(exception.message, exception.code)
view.stopSignInProgressAnimation()
}
}
}
This way you keep your natural Android programming model, which assumes the GUI thread.

BlockingGet block UI thread RxJava 2

I am dealing with the problem.
I am trying to call RxJava in the sync manner, however doing that results in blocking the Main thread.
Here is my code
#Override
public Single<SettingsBundle> getSettings() {
SettingsBundle settingsModel = mSettingsManager.getSettings();
return Single.just(settingsModel).map(mSettingsMapper);
}
And here is my sync call
#Override
public SettingsBundle getSettingsSync() {
return getSettings().blockingGet();
}
When calling the getSettingsSync the Main thread is blocked, however sometimes it works fine, what is more problematic.
I have tried something like that
#Override
public SettingsBundle getSettingsSync() {
return getSettings()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.blockingGet();
}
But it stills remains blocked.
What I am doing wrong, I would be grateful for any help.
Thanks.
TL;TR
never use observeOn(AndroidSchedulers.mainThread()) with blockingGet()
Long version
The output for:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val result =
Single.just("Hello")
.subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
.map {
println("1. blockingGet `$it` thread: ${Thread.currentThread()}")
return#map it
}
.blockingGet()
println("2. blockingGet `$result` thread: ${Thread.currentThread()}")
}
}
is
1. blockingGet `Hello` thread: Thread[RxCachedThreadScheduler-1,5,main]
2. blockingGet `Hello` thread: Thread[main,5,main]
As you can see result was generated on main thread (line 2), the map function was execute in the RxCachedThreadScheduler thread.
With the line .observeOn(AndroidSchedulers.mainThread()) decommented the blockingGet() never return and all is stucked.
.observeOn(AndroidSchedulers.mainThread())
.blockingGet();
The problem exists in this specific combination of operators. AndroidSchedulers schedules code to run on the main thread, however the blockingGet() stops more code from executing on that thread. Simply put AndroidSchedulers and the blocking operators of RxJava do not work well together.
Since the android scheduler might be used in the construction of the observable this means any use of the blocking* operators on the main thread will be prone to deadlocks regardless of what you try to do.
If you really need a function to run on the main thread and also need it to be synchronous, then you could do something like this:
If this is the main thread (Looper.myLooper() == Looper.getMainLooper()), then run func()
If not on the main thread, then you can use the combination of observeOn(AndroidSchedulers.mainThread()) with blockingGet()

onPostExecute in anko doAsync

I know there are two methods available to do AsyncTask in Anko library.
doAsync()
doAsyncResult()
My question is both the above methods have onComplete() method. In both method's onComplete() there is no trace of result like AsyncTask.onPostExecute().
Example:
doAsync {
sdkServiceFactory.initSDKService()
onComplete { Log.d("Controller", "Sdk Connected") }
}
val result = doAsyncResult {
onComplete { Log.d("Controller", "Sdk Connected") }
sdkServiceFactory.initSDKService()
}.get()
In either method, I can get only the completed callback not the result. What are the similar methods available in Anko library for AsyncTask.onPreExecute() and AsyncTask.onPostExecute().
doAsync is used to execute code on a different thread, but does not return anything to the main thread when finished.
doAsyncResult is used to perform an activity on a separate thread, and the execute an operation on the main thread after completing execution on the separate thread.
To push anything to the main thread, add a new block with
uiThread {
//write you code here
}
in it.
Or better yet, create the method that you want to run asynchronously as a function with a return value. Then pass the method in to the doAsync call. To quote an example:
val longRunningTask: (AnkoAsyncContext<ListView>.() -> ArrayList<String>) = {
::doAnIntensiveActivity.invoke()
}
val f : Future<ArrayList<String>> = doAsyncResult(null, longRunningTask)

Categories

Resources