https://kotlinlang.org logo
#android
Title
# android
b

Brais Gabin

01/22/2020, 5:02 PM
Is there any “strict mode” to check if I edit some view outside the main thread? I’m getting some strange crashes that doesn’t point to any line of my code. I think that those errors are related with a
notifyDataSetChanged
or a
setText
performed outside the main thread. The problem is that the app is huge and those errors are race exceptions so they are not easy to reproduce. For that reason I’ll need some “tool” that checks that all the interactions done with view is done in the main thread. Any idea?
t

trevjones

01/22/2020, 5:07 PM
from rxandroid MainThreadDisposable:
Copy code
if (Looper.myLooper() != Looper.getMainLooper()) {
  throw new IllegalStateException("Expected to be called on the main thread but was " + Thread.currentThread().getName());
}
I like to wrap that logic up in a function and call it from all over the points that you suspect are being accessed illegally.
requireMainThread
b

Brais Gabin

01/22/2020, 5:30 PM
Yeah… the problem is that I have no idea what’s going on >_<. For that reason I was wondering. The same way that strict mode checks that no I/O work is done in the main thread. Is there something that checks that no UI work is done outside the main thread?
t

trevjones

01/22/2020, 5:31 PM
the layout/draw system can sometimes detect it if it happens at specific timing, otherwise no I don't believe so. to which I invite peppering the code with a requireMainThread assertions
only place I can find a check in the platform so far is
android.view.ViewRootImpl#runOrPost(View source, int changeType)
which gets hit from
Copy code
notifySubtreeAccessibilityStateChanged(View child, View source, int changeType)
so only a specific set of changes checks it seems.
and viewRootImpl.checkThread
so lots of flows do check the thread
b

Brais Gabin

01/22/2020, 6:36 PM
Yes, I was looking for a way to avoid that noise in the code. But I think that I should add it for test and then remove it... The problem is the size of the project.
But thanks for the answers!
13 Views