Skip to content

Instantly share code, notes, and snippets.

@shadow7
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save shadow7/93e0809219ffffbeea04 to your computer and use it in GitHub Desktop.

Select an option

Save shadow7/93e0809219ffffbeea04 to your computer and use it in GitHub Desktop.
/**
* I use the BaseCommand class to encapsulate data used to make an Rx Observable call.
* An Rx call usually combines the action of saving a model object to firebase,
* converting the model to a RealmObject and also saving to Realm into one atomic function flow with
* an EventCallback. BaseCommands are posted from any Fragment or Activity with ProxyApplication.java's
* getRxBus().post() method. The BaseCommand is then processed in ProxyApplication which creates an
* IntentService to call the posted BaseCommand's interface ExecuteCommand, "execute()" method.
* This returns a list of events, List<EventCallback>, which contain the updated user data to
* post to subscribers of the event type.
*/
/**
* Set abstraction for a BaseCommand call.
*/
public abstract class BaseCommand implements ExecuteCommand, Parcelable {
public final ComponentName componentName;
protected BaseCommand(String packageName, String className) {
// its already parcelable, thanks android!
this.componentName = new ComponentName(packageName, className);
}
}
/**
* Require execute command in child classes.
*/
public interface ExecuteCommand {
List<EventCallback> execute(Service service);
}
/**
* Example BaseCommand, Sync All Users data from firebase to Realm and return the logged in User.
*/
public class SyncAllUsersCommand extends BaseCommand {
public static final Parcelable.Creator<SyncAllUsersCommand> CREATOR = new Parcelable
.Creator<SyncAllUsersCommand>
() {
@Override
public SyncAllUsersCommand createFromParcel(Parcel in) {
return new SyncAllUsersCommand(in);
}
@Override
public SyncAllUsersCommand[] newArray(int size) {
return new SyncAllUsersCommand[size];
}
};
private final static java.lang.ClassLoader CL =
SyncAllUsersCommand.class.getClassLoader();
public final String userId;
public SyncAllUsersCommand(String userId) {
super(SyncAllUsersCommand.class.getPackage().getName(),
SyncAllUsersCommand.class.getName());
this.userId = userId;
}
private SyncAllUsersCommand(Parcel in) {
this((String) in.readValue(CL));
}
// this is called in an IntentService and the List<EventCallback> data is returned in the
// IntentServices's result callback. This triggers a callback in ProxyApplication to query
// the new logged in User saved in Realm.
@Override
public List<EventCallback> execute(Service service) {
return RxUserSync.syncAllUsers(service, userId);
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(userId);
}
}
/**
* Cold Observables to sync users to firebase and realm.
*/
public class RxUserSync {
/**
* Private constructor.
*/
private RxUserSync() {}
/**
* Download All Users from firebase and sync them to realm. Used for swipe refresh in the {@link
* com.shareyourproxy.app.fragment.MainContactsFragment} and {@link
* com.shareyourproxy.app.fragment.MainGroupFragment}'s {@link android.support.v4.widget
* .SwipeRefreshLayout}s
*
* @param context for realm instance
* @param loggedInUserId to identify the logged in user
* @return {@link UsersDownloadedEventCallback} to rxBus
*/
public static List<EventCallback> syncAllUsers(Context context, String loggedInUserId) {
return getFirebaseUsers()
.map(updateCachedContacts(loggedInUserId))
.map(updateCachedChannels(loggedInUserId))
.map(saveRealmUsers(context))
.map(usersDownloaded(loggedInUserId))
.compose(RxHelper.<List<EventCallback>>applySchedulers()).toBlocking().single();
}
private static Func1<HashMap<String, User>, HashMap<String, User>> updateCachedChannels(
final String loggedInUserId) {
return new Func1<HashMap<String, User>, HashMap<String, User>>() {
@Override
public HashMap<String, User> call(HashMap<String, User> users) {
User loggedInUser = users.get(loggedInUserId);
for (Map.Entry<String, Channel> channelEntry : loggedInUser.channels().entrySet()) {
Channel channel = channelEntry.getValue();
String channelId = channel.id().value();
for (Map.Entry<String, Group> entryGroup : loggedInUser.groups().entrySet()) {
Group group = entryGroup.getValue();
if (group.channels().containsKey(channelId)) {
group.channels().put(channelId, channel);
}
}
}
users.put(loggedInUserId, loggedInUser);
return users;
}
};
}
private static Func1<HashMap<String, User>, HashMap<String, User>> updateCachedContacts(final String userId) {
return new Func1<HashMap<String, User>, HashMap<String, User>>() {
@Override
public HashMap<String, User> call(HashMap<String, User> users) {
User loggedInUser = users.get(userId);
//for every contact that's in the entire user list, remove the old copy and
// replace it with the new user data
for (Map.Entry<String, Contact> contactEntry : loggedInUser.contacts().entrySet()) {
for (Map.Entry<String, User> userEntry : users.entrySet()) {
if (userEntry.getKey().equals(contactEntry.getKey())) {
User userEntryValue = userEntry.getValue();
loggedInUser.contacts()
.put(userEntry.getKey(), createModelContact(userEntryValue));
}
}
}
users.put(loggedInUser.id().value(), loggedInUser);
return users;
}
};
}
private static Func1<HashMap<String, User>, HashMap<String, User>> saveRealmUsers(final Context context) {
return new Func1<HashMap<String, User>, HashMap<String, User>>() {
@Override
public HashMap<String, User> call(HashMap<String, User> users) {
updateRealmUser(context, users);
return users;
}
};
}
private static Func1<HashMap<String, User>, List<EventCallback>> usersDownloaded(final String loggedInUserId) {
return new Func1<HashMap<String, User>, List<EventCallback>>() {
@Override
public List<EventCallback> call(HashMap<String, User> users) {
User loggedInUser = users.get(loggedInUserId);
UsersDownloadedEventCallback usersCallback =
new UsersDownloadedEventCallback(loggedInUser, users);
LoggedInUserUpdatedEventCallback loggedInUserCallback =
new LoggedInUserUpdatedEventCallback(loggedInUser);
ArrayList<EventCallback> list = new ArrayList<>();
list.add(usersCallback);
list.add(loggedInUserCallback);
return list;
}
};
}
public static <T> Observable.Transformer<T, T> applySchedulers() {
return new Observable.Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> observable) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
};
}
/**
* When I debug the realm users created and saved here, they are the correct versions of data I expect.
*/
public static void updateRealmUser(Context context, Map<String, User> users) {
Realm realm = Realm.getInstance(context);
realm.refresh();
final RealmList<RealmUser> realmUsers = createRealmUsers(users);
realm.beginTransaction();
realm.copyToRealmOrUpdate(realmUsers);
realm.commitTransaction();
realm.close();
}
public static RealmList<RealmUser> createRealmUsers(Map<String, User> users) {
RealmList<RealmUser> realmUsers = new RealmList<>();
for (Map.Entry<String, User> user : users.entrySet()) {
realmUsers.add(createRealmUser(user.getValue()));
}
return realmUsers;
}
/**
* Convert User to RealmUser
*
* @param user to convert
* @return RealmUser
*/
public static RealmUser createRealmUser(User user) {
RealmUser realmUser = new RealmUser();
if (user != null) {
realmUser.setId(user.id().value());
realmUser.setFirst(user.first());
realmUser.setLast(user.last());
realmUser.setFullName(joinWithSpace(new String[]{ user.first(), user.last() }));
realmUser.setEmail(user.email());
realmUser.setProfileURL(user.profileURL());
realmUser.setCoverURL(user.coverURL());
realmUser.setChannels(getRealmChannels(user.channels()));
realmUser.setContacts(getRealmContacts(user.contacts()));
realmUser.setGroups(getRealmGroups(user.groups()));
realmUser.setMessages(getRealmMessages(user.messages()));
}
return realmUser;
}
}
/**
* Querying users or the logged in user after a BaseCommand save, delete, edit works 100% of the time,
* unless I'm updating all users specifically in the above SyncAllUsers Observable flow. Is there any to garuntee
* write transactions have completed when there is a large update of information?
* Am I using best practices and avoiding threading issues? Im very clueless as to why the event
* callback data is different that the data saved in realm.
*/
@DebugLog
public static User queryUser(Context context, final String userId) {
return Observable.just(context).map(getRealmUser(userId)).compose(RxHelper
.<User>applySchedulers()).toBlocking().single();
}
private static Func1<Context, User> getRealmUser(final String userId) {
return new Func1<Context, User>() {
@Override
public User call(Context context) {
Realm realm = Realm.getInstance(context);
realm.refresh();
realm.beginTransaction();
RealmUser realmUser =
realm.where(RealmUser.class).contains("id", userId).findFirst();
User user = UserFactory.createModelUser(realmUser);
realm.commitTransaction();
realm.close();
return user;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment