I have a "subscribe" button in one of my views that lets the user subscribe to updates on another user. The button toggles between "subscribe" and "subscribed".
Here is the activity in charge of that view:
public class ProfileActivity extends BaseActivity {
private Realm realm;
private User user;
private Subscribe subscribe = null;
private Button subscribeButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
// Get the user's information
user = (User) getIntent().getSerializableExtra("user");
subscribeButton = (Button) findViewById(R.id.subscribeButton);
// Check if already subscribed to this user
subscribe = realm.where(Subscribe.class)
.equalTo("userId", user.getId())
.findFirst();
}
// The onClick method for the subscribe button
public void subscribeToUser(View view) {
Boolean isSubscribed = subscribe != null;
realm.beginTransaction();
if (isSubscribed) {
// Unsubscribe
if (subscribe != null) {
subscribe.deleteFromRealm();
subscribe = null;
}
} else {
// Subscribe
User newUser = realm.copyToRealmOrUpdate(user);
subscribe = realm.createObject(Subscribe.class, user.getId());
subscribe.setUser(newUser);
}
realm.commitTransaction();
}
}
I'm just wondering if this is the correct way of doing this, or if there's something I should change in my code, specifically in the subscribeToUser()
method.
Thanks.