简体   繁体   中英

Android app architecture - RxJava

I am working on an android app (basically trying to get my head around using RxJava/Android). These are my requirements:

  • Maintain a persistent and global state for the logged in user
  • Whenever the user state changes, update views accordingly.

I am using a singleton User instance to maintain global state and SharedPreferences for persistence. Now I'm trying to use RxAndroid for notifying changes to the views, but I'm clueless on how to go about that.

How do we track the changes in User ? Can I use the setters in User to emit from the observables; if so, how do I go about it?

I would really appreciate if anyone can provide code samples too.

PS This is a sample of my User class definition, I haven't used any setters.

public class User {
  public String userName;
  public String emailId;
  public List<Friend> friends;

  public User() {
    friends = new ArrayList<Friend>();
  }
}

public class Friend {
  public String userName;
  public String emailId;
  public String role;
}

This is just a sample skeleton of my User class (I have stripped off everything else), I just need to know how the setters are going to look like for these fields, and if this approach is even considered right or if there are better alternatives.

Please let me know if you need more information.

i would use PublishSubject http://reactivex.io/RxJava/javadoc/rx/subjects/PublishSubject.html from RxJava and onResume/onPause of Activtiy subscribe/unsubsribe from it.

create PublishSubject inside User

public class User {
  public PublishSubject<User> stream = PublishSubject.create()
  public String userName;
  public String emailId;
  public List<Friend> friends;

  public User() {
    friends = new ArrayList<Friend>();
  }
  public void setName(String name){
         stream.onNext(this);
  }
}

So when you will use method setName of User class (Singleton as you mentioned) every thing subscribed to that steam will recive answer. like

 public class MyActivity extends Activity{

            private TextView nameTextView ;
            private Subscription subs;
            @Override
            public void onCreate{
            //initialization of fields
            }

            @Override
            public void onResume(){
              super.onResume();
              subs = User.getInstance().stream.subscribe{user-> nameTextView.setText(user.username) }
          }

             @Override
             public void onPause(){
             super.onPause();
             subs.unsubscribe();
             }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM