Design Pattern
Singleton
Just like firebase, we build a custom WebSocket singleton to control the creation of our WebSocket client, In this case, only 1 client can be created across our app, reducing the potential workload and the number of network connections to server
public class CustomWebSocket {
// websocket to ccyy.xyz for predicting and pairing functionality
private static OkHttpClient mClient;
private static CustomWebSocket myInstance;
private CustomWebSocket() {
// websocket to ccyy.xyz for pairing functionality
mClient = new OkHttpClient.Builder()
.readTimeout(3600, TimeUnit.SECONDS)
.writeTimeout(3600, TimeUnit.SECONDS)
.connectTimeout(3600, TimeUnit.SECONDS)
.build();
}
public static CustomWebSocket getInstance() {
if (myInstance == null) {
myInstance = new CustomWebSocket();
}
return myInstance;
}
public OkHttpClient getClient() {
return mClient;
}
}
Iterator
Iterator design patten here is used to create a stream of posts, iterator helps us hide the complexity of managing the counter and the post collection. Making our code much more tidy and readable
public interface Iterator {
public boolean hasNext();
public Object next();
}
public interface IterableCollection {
public Iterator createIterator();
}
/**
* Iterator pattern, used for showing post as a stream
*/
public class PostsConcreteCollection implements IterableCollection {
private ArrayList<HashMap<String, Object>> AllPostCollection = allPostItems;
@Override
public Iterator createIterator() {
return new PostsConcreteIterator();
}
private class PostsConcreteIterator implements Iterator {
int index = 0;
/**
* determine whether has next post
*
* @return True if has next post
*/
@Override
public boolean hasNext() {
if (AllPostCollection != null && index < AllPostCollection.size()) {
return true;
}
return false;
}
/**
* if has next post,get it
*
* @return next post if has next, otherwise null
*/
@Override
public Object next() {
if (this.hasNext()) {
return AllPostCollection.get(index++);
}
return null;
}
}
}
Timer timer = new Timer();
timer.schedule(new MyTask(PostActivity.this), 0, 2000);
/**
* used to give a time gap for showing new posts and show posts as a stream
*/
private class MyTask extends TimerTask {
private Activity context;
MyTask(Activity context) {
this.context = context;
}
@Override
public void run() {
context.runOnUiThread(updateThread);
}
}
Runnable updateThread = new Runnable() {
/**
* if has next post, add it and show, otherwise not update
*/
@Override
public void run() {
if (PostIterator.hasNext()) {
HashMap<String, Object> SinglePost = (HashMap<String, Object>) PostIterator.next();
BufferPostList.add(SinglePost);
}
postAdapter = new PostAdapter(getApplicationContext(), BufferPostList);
recyclerView.setAdapter(postAdapter);
}
};