How to properly use Android Room in background tasks (unrelated to UI) - java

At the moment Room is working well with a DB to UI integration:
Dao for DB operations
Repository for interacting with the Daos and caching data into memory
ViewModel to abstract the Repository and link to UI lifecycle
However, another scenario comes up which I am having a hard time understanding how to properly implement Room usage.
I have a network API that is purely static and constructed as a reflection of the servers' REST architecture.
There is a parser method that walks through the URL structure and translates it to the existing API via reflection and invokes any final method that he finds.
In this API each REST operation is represented by a method under the equivalent REST naming structure class, i.e.:
/contacts in REST equates to Class Contacts.java in API
POST, GET, DELETE in rest equates to methods in the respective class
example:
public class Contacts {
public static void POST() {
// operations are conducted here
}
}
Here is my difficulty; how should I integrate ROOM inside that POST method correctly/properly?
At the moment I have a makeshift solution which is to instantiate the repository I need to insert data into and consume it, but this is a one-off situation everytime the method is invoked since there is absolutely no lifecycle here nor is there a way to have one granular enough to be worthwhile having in place (I don't know how long I will need a repository inside the API to justify having it cached for X amount of time).
Example of what I currently have working:
public class Contacts {
public static void POST(Context context, List<Object> list) {
new ContactRepository(context).addContacts(list);
}
}
Alternatively using it as a singleton:
public class Contacts {
public static void POST(Context context, List<Object> list) {
ContactRepository.getInstance(context).addContacts(list);
}
}
Everything works well with View related Room interaction given the lifecycle existence, but in this case I have no idea how to do this properly; these aren't just situations where a view might call a network request - then I'd just use networkboundrequest or similar - this can also be server sent data without the app ever requesting it, such as updates for app related data like a user starting a conversation with you - the app has no way of knowing that so it comes from the server first.
How can this be properly implemented? I have not found any guide for this scenario and I am afraid I might be doing this incorrectly.
EDIT: This project is not Kotlin as per the tags used and the examples provided, as such please provide any solutions that do not depend on migrating to Kotlin to use its coroutines or similar Kotlin features.

Seems like using a Singleton pattern, like I was already using, is the way to go. There appears to be no documentation made available for a simple scenario such as this one. So this is basically a guessing game. Whether it is a bad practice or has any memory leak risks I have no idea because, again, there is just no documentation for this.

Related

Removing circular dependencies in asynchronous java application?

I have read up on dependency injection and interfaces, but I am still confused about the best way to decouple packages in my situation. Say I have a UIClass in UIPackage:
package UIPackage;
import NetworkPackage.NetworkClass
class UIClass() {
public static void displayMessage(String message) {
// show the message on screen
}
private static void messageEntered(String message) {
NetworkClass.sendMessage(message);
}
}
and a NetworkClass in NetworkPackage:
package NetworkPackage;
import UIPackage.UIClass;
class NetworkClass() {
public static void sendMessage(String message) {
// send the message to the network
}
private static void messageReceived(String message) {
UIClass.displayMessage(message)
}
}
These packages depend on each other, but I would like to have the network package work independently of the UI package to remove the dependency cycle. The only way I have found to do that so far is to create an interface for the UIClass to implement (UIInterface), and then an instance of UIInterface is passed to the NetworkController in the constructor or something. This seems like it just makes things more complicated though as that interface would need to be in its own package which is then included in both of the original packages.
Should I create a third package for interfaces of this type? Should I just leave the circular dependency and not worry about it?
Clarification 1
This is not the code I am actually using, I just named the packages that way so that the example would be clearer. The app uses multiple threads, which is why NetworkClass needs a references to UIClass, because it is constantly waiting for a new message while the UI may be doing other things on a different thread. When a message is received, it needs to be able to update the UI and display the message. These packages have many other classes that do other things, but for the sake of example these classes are all that is exposed.
Of course you should care, just as you should pay attention to Java coding conventions.
I think embedding "Package" in package names and "Class" in class names is brain dead. Hungarian notation fell out of favor decades ago. Take those out.
This is a bad design.
I don't know what your Network class is for. I see no reason for Network to know or care about the Client that calls it. If the Client has a reference to a Network injected into its constructor, it should be able to use it to send the call, get the response back, and display it. No good reason for giving a Client reference to Network.
No more circular dependency.
I'd expect something more like a four tier architecture:
client -> controller -> services -> persistence
This is a request/response arrangement typical of web applications. The UI sends a request to a controller/listener, which orchestrates services and persistence to fulfill the use case and send the response back to the UI.
The picture changes if you go with an asynchronous, event based architecture.
A circular dependency means generally a strong coupling between two components/things.
Is it ever a problem ?
It is very often but not always.
3 examples where it may cause an issue :
1) if the dependencies try to create themselves by passing the other as parameter. Which is obviously not possible. Using an approach that sets one of the dependency or both after instances construction is a way to solve it.
2) if the code of the dependencies changes frequently enough as a change on one class could have side effect or break the code of the other.
It is like if these classes were a single class while this is not the case.
3) if you want reuse one of the dependencies alone in other contexts or applications.
You could not as both cannot live without the other one.
So it can defeat reduce or prevent dependency reusability.

Better way to expose methods

I'm writing a database manager layer of a web service.
I have to decide ho to implement my library: this is the situation.
I have a class, PersistenceUnit:
private static RazoooCore rc;
private static DBInstance db;
protected ODatabaseDocumentTx getDb(){return db;}
protected RazoooCooore getRc(){return rc;}
public static void startPersistence (){
//here I get an instance of rc and db
}
that start my db service and allow me to connect to it. What I want is to write class that implement persistence method, like addUser(...), or deleteFile(...) and so on.
My doubt is how to realize these method. Because I have two big classes of operations (one on users and the other on files) I thought to create to class (User and File) and to implement public static method on them, or, and is the same, create two singleton.then the application layer will have to call method without having to create and destroy object each time.
Is this a good way to realize my layer? Is, in this way, well handled concurrency, or is there a better way (perhaps a pattern) to maximize performance and multithreading?
Certainly this is not a memory-bound layer, because upper layer doesn't have to continuously
create object.
Thank you
There were lots of discussions about if an object should (or not) be responsible of persist itself, this is, should an User class have a Save method? Well, it depends. However, currently we hardly ever see that pattern.
I think the persistence logic has to be in a data access layer, probably in repositories (UserRepository and FileRepository). And this has nothing to do with neither performance nor multithreading because both issues (performance and concurrency) are in the database.
That´s my opinion.

How can I change my Java program to use a database instead of an arraylist?

In my java program, I had a book class and a library class.
The library stores the book object in an array list and then I display it on the screen.
I can add the book and remove the books using functions.
I also use AbstractJtableModel for adding and removing the books.
But now I want to use a database, MySQL, instead of an array list.
How should I change my program?
well, you need to write the whole application :)
you need to create a db, with at least one table, you need to add mysql jdbc library to classpath and using jdbc you can insert/select/update/delete data from DB.
Alternatively, you need to add jdbc and use ORM framework like Hibernate, but depending on your Java knowledge this way can be harder (but easier to maintain in future, if you create big application). Here you can download simple hibernate application, which does CRUD operations with Honey :), you can extract interface similar to suggested by Javid Jamae from TestExample class, and exchange Honey class with Book according to your needs
You might consider using the Data Access Object (DAO) pattern. Just do a Google search and you'll find tons of articles on the topic. Essentially, you'll create a LibraryDao interface with methods like:
public interface LibraryDao {
public void storeLibrary(Library library)
public Library loadLibrary(long id)
public List<Library> searchByTitle(String title)
//...
}
You can implement this interface with straight SQL, or you can use an Object Relational Mapping (ORM) tool to implement it. I highly recommend reading up on Hibernate and the JPA specification.
Abstract the retrieval and storage of the books into a class by itself - you don't want that persistence logic intermingled with your business logic. I'd suggest creating an interface called something like "BookStorageDAO" and then you can have various implementations of that interface. One implementation may be to store the books in an ArrayList while another may be to store the books in a Database.
In this way, you can utilize the interface in your business logic and swap out the implementation at any time.
You would still use the ArrayList in your GUI to persist and display the data. The difference would be you need logic to save and load that ArrayList from a database so that the data is stored even after the program ends.
Side note, extends DefaultTableModel as opposed to AbstractJtabelModel. It completes some of the methods for you.
You don't need a DAO per se, but those answers aren't wrong.
Separation of Concern
What you need to do is separate your application based on concern, which is a pattern called separation of concern. It's a leak to have concerns overlap, so to combat this, you would separate your application into layers, or a stack, based on concern. A typical stack might be include:
Data Access Layer (read/write data)
Service Layer (isolated business logic)
Controller (Link between view and model)
Presentation (UI)
etc., but this will only partly solve your problem.
Program To The Interface
You also (as the others have mentioned) need to abstract your code, which will allow you to make use of dependency injection. This is extremely easy to implement. All you have to do is program to the interface:
public interface PersonService {
public List<Person> getAllPersons();
public Person getById(String uuid);
}
So your application would look like this:
public class PersonApp {
private final PersonService personService;
public PersonApp(PersonService personService) {
this.personService = personService;
}
}
Why is this better?
You have defined the contract for interacting with the Person model in the interface, and your application adheres to this contract without having any exposure to the implementation details. This means that you can implement the PersonService using Hibernate, then later decide you want to use JPA, or maybe you use straight JDBC, or Spring, etc. etc., and even though you have to refactor the implementation code, your application code stays the same. All you have to do is put the new implementation on the classpath and locate it (tip: the Service Locator pattern would work well for that).

Getting to Guice created objects from dumb data objects

I've taken the plunge and used Guice for my latest project. Overall impressions are good, but I've hit an issue that I can't quite get my head around.
Background: It's a Java6 application that accepts commands over a network, parses those commands, and then uses them to modify some internal data structures. It's a simulator for some hardware our company manufactures. The changes I make to the internal data structures match the effect the commands have on the real hardware, so subsequent queries of the data structures should reflect the hardware state based on previously run commands.
The issue I've encountered is that the command objects need to access those internal data structures. Those structures are being created by Guice because they vary depending on the actual instance of the hardware being emulated. The command objects are not being created by Guice because they're essentially dumb objects: they accept a text string, parse it, and invoke a method on the data structure.
The only way I can get this all to work is to have those command objects be created by Guice and pass in the data structures via injection. It feels really clunky and totally bloats the constructor of the data objects.
What have I missed here?
Dependency injection works best for wiring services. It can be used to inject value objects, but this can be a bit awkward especially if those objects are mutable.
That said, you can use Providers and #Provides methods to bind objects that you create yourself.
Assuming that responding to a command is not that different from responding to a http request, I think you're going the right path.
A commonly used pattern in http applications is to wrap logic of the application into short lived objects that have both parameters from request and some backends injected. Then you instantiate such object and call a simple, parameterless method that does all magic.
Maybe scopes could inspire you somehow? Look into documentation and some code examples for read the technical details. In code it looks more less like that. Here's how this might work for your case:
class MyRobot {
Scope myScope;
Injector i;
public void doCommand(Command c) {
myScope.seed(Key.get(Command.class),
i.getInstance(Handler.class).doSomething();
}
}
class Handler {
private final Command c;
#Inject
public Handler(Command c, Hardware h) {
this.c = c;
}
public boolean doSomething() {
h.doCommand(c);
// or c.modifyState(h) if you want c to access internals of h
}
}
Some people frown upon this solution, but I've seen this in code relying heavily on Guice in the past in at least two different projects.
Granted you'll inject a bit of value objects in the constructors, but if you don't think of them as value objects but rather parameters of the class that change it's behaviour it all makes sense.
It is a bit awkward and some people frown upon injecting value objects that way, but I have seen this in the past in projects that relied heavily on Guice for a while and it worked great.

Exposing a remote interface or object model

I have a question on the best way of exposing an asynchronous remote interface.
The conditions are as follows:
The protocol is asynchronous
A third party can modify the data at any time
The command round-trip can be significant
The model should be well suited for UI interaction
The protocol supports queries over certain objects, and so must the model
As a means of improving my lacking skills in this area (and brush up my Java in general), I have started a project to create an Eclipse-based front-end for xmms2 (described below).
So, the question is; how should I expose the remote interface as a neat data model (In this case, track management and event handling)?
I welcome anything from generic discussions to pattern name-dropping or concrete examples and patches :)
My primary goal here is learning about this class of problems in general. If my project can gain from it, fine, but I present it strictly to have something to start a discussion around.
I've implemented a protocol abstraction which I call 'client' (for legacy reasons) which allows me to access most exposed features using method calls which I am happy with even if it's far from perfect.
The features provided by the xmms2 daemon are things like track searching, meta-data retrieval and manipulation, change playback state, load playlists and so on and so forth.
I'm in the middle of updating to the latest stable release of xmms2, and I figured I might as well fix some of the glaring weaknesses of my current implementation.
My plan is to build a better abstraction on top of the protocol interface, one that allows a more natural interaction with the daemon. The current 'model' implementation is hard to use and is frankly quite ugly (not to mention the UI-code which is truly horrible atm).
Today I have the Tracks interface which I can use to get instances of Track classes based on their id. Searching is performed through the Collections interface (unfortunate namespace clash) which I'd rather move to Tracks, I think.
Any data can be modified by a third party at any time, and this should be properly reflected in the model and change-notifications distributed
These interfaces are exposed when connecting, by returning an object hierarchy that looks like this:
Connection
Playback getPlayback()
Play, pause, jump, current track etc
Expose playback state changes
Tracks getTracks()
Track getTrack(id) etc
Expose track updates
Collections getCollection()
Load and manipulate playlists or named collections
Query media library
Expose collection updates
For the asynchronous bit, I would suggest checking into java.util.concurrent, and especially the Future<T> interface. The future interface is used to represent objects which are not ready yet, but are being created in a separate thread. You say that objects can be modified at any time by a third party, but I would still suggest you use immutable return objects here, and instead have a separate thread/event log you can subscribe to to get noticed when objects expire. I have little programming with UIs, but I believe using Futures for asynchronous calls would let you have a responsive GUI, rather than one that was waiting for a server reply.
For the queries I would suggest using method chaining to build the query object, and each object returned by method chaining should be Iterable. Similar to how Djangos model is. Say you have QuerySet which implements Iterable<Song>. You can then call allSongs() which would return a result iterating over all Songs. Or allSongs().artist("Beatles"), and you would have an iterable over all Betles songs. Or even allSongs().artist("Beatles").years(1965,1967) and so on.
Hope this helps as a starting place.
Iterable only has the method Iterator get() or somesuch. So no need to build any query or execute any code until you actually start iterating. It does make the execute in your example redundant. However, the thread will be locked until the first result is available, so you might consider using an Executor to run the code for the query in a separate thread.
#Staale
It is certainly possibly, but as you note, that would make it blocking (at home for something like 10 seconds due to sleeping disks), meaning I can't use it to update the UI directly.
I could use the iterator to create a copy of the result in a separate thread and then send that to the UI, but while the iterator solution by itself is rather elegant, it won't fit in very well. In the end, something implementing IStructuredContentProvider needs to return an array of all the objects in order to display it in a TableViewer, so if I can get away with getting something like that out of a callback... :)
I'll give it some more thought. I might just be able to work out something. It does give the code a nice look.
#Staale: Thanks a bunch!
Using Future for the async operations is interesting. The only drawback being that it is doesn't provide callbacks. But then again, I tried that approach, and look where that got me :)
I'm currently solving a similar problem using a worker thread and a blocking queue for dispatching the incoming command replies, but that approach doesn't translate very well.
The remote objects can be modified, but since I do use threads, I try to keep the objects immutable. My current hypothesis is that I will send notification events on track updates on the form
somehandlername(int changes, Track old_track, Track new_track)
or similar, but then I might end up with several versions of the same track.
I'll definitely look into Djangos method chaining. I've been looking at some similar constructs but haven't been able to come up with a good variant. Returning something iterable is interesting, but the query could take some time to complete, and I wouldn't want to actually execute the query before it's completely constructed.
Perhaps something like
Tracks.allSongs().artist("Beatles").years(1965,1967).execute()
returning a Future might work...
My conclusions so far;
I am torn on whether to use getters for the Track objects or just expose the members since the object is immutable.
class Track {
public final String album;
public final String artist;
public final String title;
public final String genre;
public final String comment;
public final String cover_id;
public final long duration;
public final long bitrate;
public final long samplerate;
public final long id;
public final Date date;
/* Some more stuff here */
}
Anybody who wants to know when something happened to a track in the library would implement this...
interface TrackUpdateListener {
void trackUpdate(Track oldTrack, Track newTrack);
}
This is how querys are built. Chain calls to your hearts content. the jury is still out on the get() though. There are some details missing, such as how I should handle wildcards and more advanced queries with disjunctions. I might just need some completion callback functionality, perhaps similar to the Asynchronous Completion Token, but we'll see about that. Perhaps that will happen in an additional layer.
interface TrackQuery extends Iterable<Track> {
TrackQuery years(int from, int to);
TrackQuery artist(String name);
TrackQuery album(String name);
TrackQuery id(long id);
TrackQuery ids(long id[]);
Future<Track[]> get();
}
Some examples:
tracks.allTracks();
tracks.allTracks().artist("Front 242").album("Tyranny (For You)");
The tracks interface is mostly just the glue between the connection and the individual tracks. It will be the one implementing or managing meta-data caching, if any (as today, but I think I'll just remove it during the refactoring and see if I actually need it). Also, this provides medialib track updates as it would just be too much work to implement it by track.
interface Tracks {
TrackQuery allTracks();
void addUpdateListener(TrackUpdateListener listener);
void removeUpdateListener(TrackUpdateListener listener);
}

Categories

Resources