我是否正确实现了android的mvvm架构模式?

jaql4c8m  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(254)

如果能从更有经验的开发人员那里获得对我的mvvm实现的意见,那将是一个巨大的帮助。我研究android推荐的应用程序架构模式已经有一段时间了。在我确信自己对mvvm应该如何工作有了一个不错的想法之后,我开始更新正在进行的应用程序的代码库,以便更好地遵循mvvm实践。在很大程度上,它的实现非常简单,而且非常容易(多亏了google和你们在stackoverflow上的帮助)。然而,一直困扰我的是如何正确处理事件和导航。
是的,我知道,这个网站上有很多答案可以回答这个问题。唯一的问题是,几乎每一个问题的答案都不尽相同,而且似乎都比实际情况复杂一些。不管怎样,我不是在寻找这些问题的答案。
相反,我希望我能得到一个更有经验的开发人员的意见,看看我的这一小部分代码是否符合mvvm的要求。我之所以提出处理事件和导航,是因为下面的代码处理了非常简化的导航和事件处理(只需在单击按钮后结束活动的生命周期)。我认为我遵循了mvvm实践,但我不是100%肯定,而且没有官方文档指定如何做这样的事情,至少我没有见过。
不管怎样,我会在下面粘贴相关的代码,我会尽我所能省略任何现在不在审查范围内的内容。

创建活动

***注意,在 onCreate 以及 onOptionsItemSelected 方法

public class CreateActivity extends AppCompatActivity {

    private static final String TAG = "CreateActivity";
    private EditText searchNameEditText;
    private Spinner modelSpinner;
    private EditText yearEditText;
    private EditText trimEditText;
    RangeSlider priceSlider;
    private CreateViewModel createViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        instantiateUI();

        createViewModel = new ViewModelProvider(this).get(CreateViewModel.class);

        // Observes a MutableLiveData and kills the activity when the data is updated (the value of the 
        // data doesn't matter)
        createViewModel.getCreateCancelled().observe(this, isCancelled -> finish());

        // Observes a MutableLiveData and uses Toast to show the String value when it is updated
        createViewModel.getToastMessage().observe(this, message ->
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show());

    }

    public void createNewSearch() {

        String searchName = searchNameEditText.getText().toString();
        String model = modelSpinner.getSelectedItem().toString();
        String trim = trimEditText.getText().toString();
        String year = yearEditText.getText().toString();

        List<Float> priceValues = priceSlider.getValues();
        String minPrice = Collections.min(priceValues).toString();
        String maxPrice = Collections.max(priceValues).toString();

        // Calls method in ViewModel to create new "search" then kills the activity
        createViewModel.create(searchName, model, trim, year, minPrice, maxPrice);
        finish();

    }

    private void instantiateUI() {

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        searchNameEditText = findViewById(R.id.et_search_name);
        modelSpinner = findViewById(R.id.spinner_model);
        trimEditText = findViewById(R.id.et_trim);
        yearEditText = findViewById(R.id.et_year);
        priceSlider = findViewById(R.id.slider_price);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.models__array, R.layout.create_list_item);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        modelSpinner.setAdapter(adapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Calls a method in ViewModel to handle event
        createViewModel.handleOnOptionsItemSelected(item.getItemId());
        return super.onOptionsItemSelected(item);
    }
}

创建视图模型

public class CreateViewModel extends AndroidViewModel {

    private static final String TAG = "CreateViewModel";
    private SearchRepository repository;
    private MutableLiveData<String> toastMessage;
    private MutableLiveData<Boolean> createCancelled;

    public CreateViewModel(Application application) {
        super(application);
        repository = new SearchRepository();
        toastMessage = new MutableLiveData<>();
        createCancelled = new MutableLiveData<>();
    }

    public void create(String name, String model, String trim, String year, String minPrice, String maxPrice) {
        repository.create(name, model, trim, year, minPrice, maxPrice);
    }

    public MutableLiveData<String> getToastMessage() {
        return toastMessage;
    }

    // Updating the value in toastMessage will trigger a Toast message in the view
    public void setToastMessage(String message) {
        toastMessage.postValue(message);
    }

    public MutableLiveData<Boolean> getCreateCancelled() {
        return createCancelled;
    }

    // Called when MenuItem is clicked and triggers the view to kill the activity
    public void handleOnOptionsItemSelected(int itemId) {
        if (itemId == android.R.id.home)
            createCancelled.postValue(true);
    }
}

搜索存储库

public class SearchRepository {

    private static final String TAG = "SearchRepository";
    private static final FirebaseAuth AUTH_REF = FirebaseAuth.getInstance();
    private static final DatabaseReference DATABASE_REF = FirebaseDatabase.getInstance().getReference();

    public SearchRepository() {
    }

    // Called from the CreateViewModel -- creates a new "search"
    public void create(String name, String model, String trim, String year, String minPrice, String maxPrice) {

        //TODO-- Add completed check and return boolean to confirm success
        final String KEY = DATABASE_REF.child("queries").child(AUTH_REF.getCurrentUser().getUid()).push().getKey();
        SearchModel searchModel = new SearchModel(KEY, name, model, trim, year, minPrice, maxPrice);

        // The WebScraper class saves the new "search" and its results to the Firebase Database
        WebScraper scraper = new WebScraper(searchModel, DATABASE_REF, AUTH_REF.getCurrentUser().getUid());
        scraper.execute();
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题