Recently, I try to use MVP Pattern in my android project.
I know that I can't do bussiness logic job in View layer. View must deliver all works to Presenter layer then wait for the result from Presenter.
View should do anything in UI thread. But Presenter may do something in Sub-Thread.
How do I control MultiThreading in View layout and Preseneter layer?
Any help will be highly appreciated.
You have two directions you need to communicate:
a) non-UI to UI thread
and
b) UI thread to non-UI thread.
For the first case, a popular way these days is to use runOnUiThread()
Here's a nice survey of this technique and other popular options:
http://www.intertech.com/Blog/android-non-ui-to-ui-thread-communications-part-1-of-5/
As for the other direction, it is not typically necessary unless you have slow blocking operations. It is more a question of clean organization of your source code. A modern technique for sending results back from View to Presenter is using custom interfaces in Fragments like this in the "Communicating with the Activity" section:
http://developer.android.com/guide/components/fragments.html
Note that you should not put long running operations on the UI thread because it will make your app feel sluggish. Try to run them on a different thread if they will take more than 50 milliseconds or so.
Android already separates the functionality of the UI and the controller (or Presenter). It's really your job to separate it even more to make it follow the MVP pattern stronger. The view is on its own thread separate from your presenters. You won't need to do anymore threading for that unless you'd like to for whatever reason.
When I say separating it farther I just mean implementing a structure that abstracts the handling of data to be able to be reused or changed easily.
Related
AFAIK, android uses Single thread architecture, where all UI components event are dispatched,i.e. main thread or UI thread.
But why we cannot perform UI operations on separate thread other than main thread?
The main problem is related to the context. In a background thread you could update some UI stuff which is not in the current context. This is one of the reason.
UPDATE:
From the Android developer guide:
Additionally, the Andoid UI toolkit is not thread-safe. So, you must
not manipulate your UI from a worker thread—you must do all
manipulation to your user interface from the UI thread. Thus, there
are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
You can read more on thread safety from [1] [2] and you can read even [3] with a small exmaple and explenation!
Hope that now it is more clear sorry for the short and quick answer before :)
Well, first of all I need to state that this is a design level problem that has been discussed by many generations of programmers :)
Now technical details:
A GUI framework is a very complex thing. A GUI framework needs to display (draw) certain views (or windows) and route external (mostly user) inputs to the view that the input is targeted to. Now, to manage the screen with views with proper event dispatch to each view, all views shall be part of a graph and the simplest form of such a graph is a tree. So, you essentially have a tree of views to manage - where information should be fed to a root view from where your whole event routing takes place to child views.
Naturally, one dedicated thread to do manage this view hierarchy and event routing by monitoring a message queue to which all these drawing and input events are posted - by itself or any other threads - is a neat and simple solution. Any other solution that involves more than a thread will make the already complex view management and event routing code prone to dead/live locks.
Along with these technical details, you need to keep it in mind that you are trying to do business with a framework which is going to be used by other people who usually don't have faintest idea about the inner details of your architecture. Introduce threading support in such a framework is an open invitation for synchronization bugs (read: deadlocks, grumpy end users who are programmers AND ultimately bad business).
Android (and 99% other GUI toolkits) adopts this method. Simply because it makes things simpler and less error prone to have one main thread to deal with all error prone processing. All other threads are free to request it to do things by posting messages to the main thread's message queue. It is a balance between complexity and stability.
The only drawback of this approach is smooth updates of views - if you have many views to update simultaneously, OR your view hierarchy itself is really nested and complex. This drawback of this single threaded architecture manifest itself in pretty obvious forms in Android like:
Animating multiple views simultaneously is never smooth - unlike iOS where they have taken the pains to move certain parts of this operation to more than one threads of execution.
Android documentation need to remind the programmer all the time not to do lengthy operations in main thread AND to avoid deeply nested view hierarchies.
When I design models layer, there are two way to design my interface. Synchronized or asynchronized.
A. asynchronized design:
interface Callback<T> {
void success(T t);
void failure(Throwable err);
}
interface UserAPI {
void getProfile(Callback<User> callback);
}
B. Synchronized Design
interface UserAPI {
User getProfile();
}
They both have some benefit. A is non-blocking, the UI layer can use it directly. B is blocking, but it is easy to test, the design is much simple, but the UI layer should make a thread to handle it.
I really care about agility development, easy to maintain, keep the whole project neat. Which design should I use?
Ultimately, this is more a question of what you want your API to accomplish, how easy is it to use, performance impact, etc. Asynchronous designs, when done correctly, can help with some performance and API usage restrictions. But, they also tend to be harder to implement correctly and even understand by end users. Synchronous APIs tend to be easier to understand, but come with more restrictions (as you noted with use on the UI thread.) As far as backing implementation, async can also be harder to understand and maintain. I don't think agile development models really influence this, as well as the project maintenance. I would try to ensure those working on it (employees, open source contributors, etc.) are good developers who understand both approaches, write easy to understand and well structured code, and understand the goal of the API.
My recommendation: implement an API which has both async and sync versions available. Maximum flexibility, best of both worlds. Just be sure to document both sets of APIs so users know the semantics of using both.
I think it depends on a particular task. You can't choose either way for the whole project, as it usually consists of multiple parts. As a general rule, each task should be reduced to the synchronous behavior whenever it's possible, for the sake of simplicity.
If an operation is done over a fixed period of time and isn't much
longer than other operations, you can call it synchronously in the
UI thread.
If the execution of an operation may take long or unlimited period
of time, or it depends on some external conditions (e.g. network
connection, system load) and doesn't interact with the UI layer, then I'd use the synchronous design in a background thread.
If the same operation as in the previous paragraph causes updates to the GUI, then obviously the async design should be implemented.
Internal use
I would say it depends on how you will be using this API interface. If it's going to be used internally then it's a matter of where would you like to handle background threads. It's completely up to you.
Published API
In case your API is going to be published then actually it depends on developers needs. Some like to handle threading by them self deciding if it's going to be a single thread queue, multithreaded simultaneously solution or combination of both. For them SYNC API is perfect.
On the other hand some developers may not care about threading and just want get the result as easier as possible. For them ASYNC is perfect.
Recommendation
So it's seem that most probably you will have to implement both. It's most appreciated by developers and reach wide audience. For example have a look at one of the most popular network API Retrofit. They probably had the same decision to make and they implemented SYNC and ASYNC.
RETROFIT SYNC EXAMPLE
#GET("/user/{id}/photo")
Photo getUserPhoto(#Path("id") int id);
RETROFIT ASYNC EXAMPLE
#GET("/user/{id}/photo")
void getUserPhoto(#Path("id") int id, Callback<Photo> cb);
As we know, when we update the UI from the non-ui-thread, we use Handler or AsyncTask. We can find a lot of articles on how to use these methods on the Internet. But I cannot find an explanation on why a UI element cannot be operated from the non-ui thread? Can anyone help me?
I believe this decision was made by the Android team (and many other UI frameworks for that matter) because of the following reasons
Synchronization
Security
Performance
Synchronization
The simplest reason for following a single threaded model for UI is that it is the easiest way to ensure that the User Interface is not being updated by multiple sources at once and therefore, corrupted. If you imagine that multiple threads can modify the UI, it would take each thread its own amount of time to execute a portion of its code, and with the different execution speeds generate a bad user experience.
Security
Ensuring that one thread can access the UI is also a security measure, preventing any slave threads that accidentally (or purposefully) try to corrupt the UI from doing so, simply by not allowing it.
Performance
The core fact of the matter here is that UI operations, and re-rendering and re-drawing visual layers and elements is an expensive process. It can affect the performance of the framework and cause leaks or lags with the deadlocks and synchronisation in-between. So I believe this was done for the sake of performance too :)
I suspect it's because a UI is a state machine, having multiple threads operate on a single state machine makes it difficult or impossible to reason about the current state of the UI and what transitions are available at any given time. There would be unpredictable results, so it's best to keep it separated from code executing in an AsyncTask.
I'm developing an app in which I pretend to invoke a REST service for typical CRUD operations. Since I want to separate the requests processing from the UI thread, I'm planning to use an AsyncTask to do the separate work. However, my question here is: how should I desing my AsyncTask(s) model? Should I use one AsyncTask for all CRUD operations (is this even feasible?), or use i.e. 4 AsyncTasks (create, delete, update, retrieve)?
Thanks in advance
I would go with a ContentProvider instead of using AsyncTask.
According to this thread:
https://groups.google.com/forum/?fromgroups#!topic/android-developers/8M0RTFfO7-M%5B1-25%5D
on Android 4 AsyncTasks will be sequential.
So, for that reason alone your solution may be less than optimal.
But, ContentProvider just makes more sense for what you are trying to do, as what happens behind the CRUD calls the user doesn't care. You may want to run this on a separate thread though, as being on the UI thread for too long is bad.
It is really up to you, and perhaps, the REST service which you are consuming.
Some things to consider:
Is the service general enough that it would be easy to do everything in a with a single AsyncTask?
Will your code be easier to read and understand if you do things with a single AsyncTask? I would tend to think that it would be easier to read if you did one AsyncTask for each operation. (ie, CreateTask, UpdateTask...)
Will I get the reusability that I am after with my choice (whatever it is)?
Personally, I would create 4 distinct AsyncTask's, and any reusable code I might put in a base class, but again, it is really up to you for what is going to work best for you.
Personally, I use the Loader framework, available with the compatibility library. I have a subclass of AsyncTaskLoader for each of the CRUD operations, and it works really well!
I guess if you prefer to avoid having lots of classes you could use the same task (i.e. the create and update could technically fit in the same task) - when you subclass your AsyncTaskLoader create a setParameters(...) method which you can call when you create the loader in onCreateLoader().
It might help to read the above after you've reviewed the Loader documentation.
writing a small android game for a university assignment and just wanted to check what I'm doing is correct.
I'm creating a Mastermind type game and am unsure how to handle basic game operations such as checking if a guess is correct.
Am I correct in thinking that the best way to handle these operations is to create inner classes that extend Async to avoid UI lockup?
If not could anyone suggest any other ways?
Cheers!
After many weeks of developing my application, AsyncTask is what I used instead of standard threads. AyncTasks are less likely to get killed, they create a worker thread and handlers by themselves so you can update GUI through it more easily than standard threads. But remember that only one instance of AsyncTask can work at a time.
I don't think you need AsyncTask for this game at all. AsyncTask is a process for which you do not know how long it will take and you don't want to block your UI thread, like downloading something from Internet.
Your game can be completly events driven. Whenever the user makes a move you call your methods.
If you want to have animations while the user thinks then SurfaceView can do the job.