Jetpackjetpack

Jetpack mvvm 三部曲(二) LiveData

2020-09-30  本文已影响0人  三月四晴

在上篇讲了下ViewModel 这次接着讲LiveData

下一篇 Jetpack mvvm 三部曲(三) DataBinding
先放下本jetpak系列在学习过程写的demojetpackDemo
    implementation 'androidx.lifecycle:lifecycle-livedata:2.2.0'
官方提示
public class MyViewModel extends ViewModel {

    public MutableLiveData<String> stringMediatorLiveData;

    public MyViewModel() {
        stringMediatorLiveData = new MutableLiveData<>();
    }

}

  MyViewModel  viewModel = new ViewModelProvider(this).get(MyViewModel.class);
        viewModel.stringMediatorLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.e("MainActivity",s+"----");
            }
        });
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.stringMediatorLiveData.setValue("哈哈哈哈");    
            }
        });

-------------------------------分割线-------------------------------

public class MyViewModel extends ViewModel {
    private MutableLiveData<String> stringMediatorLiveData;
    public LiveData<String> stringLiveData;

    public MyViewModel() {
        stringMediatorLiveData = new MutableLiveData<>();
        stringLiveData = stringMediatorLiveData;
        this.user = new User("张三",11);
        this.count = 13;
    }

    public void update(String s){
        stringMediatorLiveData.setValue(s);
    }
}
 MyViewModel  viewModel = new ViewModelProvider(this).get(MyViewModel.class);
        viewModel.stringLiveData.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.e("MainActivity",s+"----");
            }
        });
       
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewModel.update("哈哈哈哈");
            }
        });

-------------------------------分割线-------------------------------

如果就想去实时监听数据更新不管页面可见不可见那怎么办

  Observer<Integer> integerObserver = new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                Log.e("LiveDataActivity",string+"--->"+integer);
            }
        };
        model.time.observeForever(integerObserver);
在扯下MediatorLiveData
  public MutableLiveData<String> message = new MutableLiveData<>();
  public MediatorLiveData<Integer> messageNumber = new 
  MediatorLiveData<>();
  messageNumber.setValue(0);
  messageNumber.addSource(message, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                messageNumber.setValue(s.length());
        }
 });
<LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/edit"
            android:layout_width="200dp"
            android:layout_marginLeft="10dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:text="@={mode.message}"
            android:singleLine="true"
            android:background="@drawable/b2"
            android:layout_height="50dp"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:textColor="#cc00"
            android:text='@{String.format("输入了%d个字",mode.messageNumber)}'
            android:layout_height="wrap_content"/>
    </LinearLayout>
   @Override
    protected void onCleared() {
        super.onCleared();
        messageNumber.removeSource(message);
    }
总结下
最后在说1个东西转换
map
public class LiveDataViewModel extends ViewModel {
    private MutableLiveData<User> userMutableLiveData;
    public LiveData<Integer> age;
    
    private List<User> users;
    public LiveDataViewModel() {
        userMutableLiveData = new MutableLiveData<>();
        age = Transformations.map(userMutableLiveData, new Function<User, Integer>() {
            @Override
            public Integer apply(User input) {
                return input.getAge();
            }
        });
     public void addUser(User user){
        //这里值得注意的是setValue主线程用没问题,如果是子线程那就要用postValue
        // userMutableLiveData.postValue(user);
        if(Looper.myLooper() == Looper.getMainLooper()){
            userMutableLiveData.setValue(user);
        }else {
            userMutableLiveData.postValue(user);
        }
    }
}
   model.age.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                Log.e("MainActivity",integer+"--");
            }
        });
switchMap
public class LiveDataViewModel extends ViewModel {
    public LiveData<User> userLiveData;
    private MutableLiveData<Integer> userIndex = new MutableLiveData<>();

    private List<User> users;
    public LiveDataViewModel() {
        users = new ArrayList<>();
        users.add(new User("李四",16));
        users.add(new User("张三",18));
        users.add(new User("王武",17));
        users.add(new User("钱六",20));
        userLiveData =  Transformations.switchMap(userIndex, new Function<Integer, LiveData<User>>() {
            @Override
            public LiveData<User> apply(Integer input) {
                return getUser(input);
            }
        });
    }
    public void queryUser(int userId){
        userIndex.setValue(userId);
    }
    //模拟查询
    public  LiveData<User> getUser(int userId){
        MutableLiveData<User> userMutableLiveData = new MutableLiveData<>();
        if(userId>users.size()-1){
            userMutableLiveData.setValue(new User("没有该用户",0));
            return userMutableLiveData;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                userMutableLiveData.postValue(users.get(userId));
            }
        }).start();
        return userMutableLiveData;
    }
}
    model.userLiveData.observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                dataBinding.name.setText("名字:"+user.getName());
                dataBinding.tvAge.setText("年龄:"+user.getAge());

            }
        });
最后的最后说下onChanged回调是在主线程的,不然会抛异常这也解释了子线程得用postValue去更新数值

到此LiveData便就结束了 写的不对不好的地方请大家指点

上一篇下一篇

猜你喜欢

热点阅读