I want to try Loaders. But when i call initLoader() like it's done in the documentation, the UI-Thread is getting blocked with the code from onCreateLoader. Isn't that the whole point of Loaders? Why is that, and what should i do to prevent the UI-Thread from beeing blocked here? I am using debugging in Android Studio on the Nexus 5.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_provider_test);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader onCreateLoader(int loaderID, Bundle args) {
//Do nothing 100000000 times
for(int i=0; i< 100000000; i++)
;
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
//nothing to display
}
@Override
public void onLoaderReset(Loader loader) {
//nothing to reset
}
Once you call await() , you're suspending the function call, effectively avoiding blocking the thread.
mainThread() is the scheduler associated with the main thread. Given that our API call is mRestApi. getData() and it returns a Data object, the basic call can look like this: Observable.
A Service is an Android application component without a UI that runs on the main thread (of the hosting process). It also has to be declared in the AndroidManifest. xml. If you want the service code to run in a Background Thread, then you must manage that yourself.
There're 3 types of thread: Main thread, UI thread and Worker thread. Main thread: when an application is launched, the system creates a thread of execution for the application, called main.
But when i call initLoader() like it's done in the documentation, the UI-Thread is getting blocked with the code from onCreateLoader.
As Luksprog notes, onCreateLoader()
is called on the same thread that initLoader()
is called on, and usually that is the main application thread. The job of onCreateLoader()
to create the Loader
, as you might have guessed by the name.
Isn't that the whole point of Loaders?
The point of a Loader
is to load data. The point of an AsyncTaskLoader
is to load data asynchronously. You are welcome to create some other Loader
that does not inherit from AsyncTaskLoader
, in which case doing the loading asynchronously is your job.
what should i do to prevent the UI-Thread from beeing blocked here?
Write a correct implementation of onCreateLoader()
, one that creates a Loader
instance and returns it, rather than looping 100000000 times and then returning null
.
This is covered in the documentation on the Loader
framework.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With