1. 程式人生 > >一個簡單的MVVM Demo

一個簡單的MVVM Demo

public class TestActivity extends FragmentActivity {
    Lifecycle lifecycle;
    TestViewModel testViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lifecycle = getLifecycle();
        testViewModel = ViewModelProviders.of(this).get(TestViewModel.class);
        testViewModel.getAfterTask().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                //dosomthing UI 
            }
        });

    }

}

Activity部分

 

ViewModel部分


public class TestViewModel extends AndroidViewModel {

    public MutableLiveData<Boolean> afterTask;
    public TestViewModel(@NonNull Application application) {
        super(application);
    }

    public void doSomeThing(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //do somthimg
                getAfterTask().postValue(true);
            }
        }).start();
    }

    public MutableLiveData<Boolean> getAfterTask(){
        if(afterTask == null){
            afterTask = new MutableLiveData<>();
        }
        return afterTask;
    }
}

非同步執行任務,然後activity中去改變Ui