适当的方式来阻止Android AndroidViewModel和LiveData

时间:2017-06-26 08:14:24

标签: android viewmodel android-livedata

我在我的项目中实现了LiveData,但我对它有点困惑。它有效,但我不知道这是正确的方法。

我的实时数据类:

    public class ClientLiveData extends LiveData<List<Client>> {
    private Context context;
    private BroadcastReceiver dataChangedReciever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Logger.logLiveData("Data changed");
            loadData();
        }
    };

    public ClientLiveData(Context context) {
        this.context = context.getApplicationContext();
        loadData();
    }

    @Override
    protected void onActive() {
        super.onActive();
        Logger.logLiveData("Activate live data");
        LocalBroadcastManager.getInstance(context).registerReceiver(dataChangedReciever, new IntentFilter(DpnPreferences.DATA_CHANGED_FILTER));
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        Logger.logLiveData("Inactivate live data");
        LocalBroadcastManager.getInstance(context).unregisterReceiver(dataChangedReciever);
    }

    private void loadData() {
        new AsyncTask<Void, Void, List<Client>>() {
            @Override
            protected List<Client> doInBackground(Void... params) {
                Logger.logLiveData("Loading data");
                IClientDao clientDao = new DaoFactory().getClientDao();
                List<Client> clients = clientDao.getAllClients();
                Logger.logLiveData("Loading clients "+clients.size());
                return clients;
            }

            @Override
            protected void onPostExecute(List<Client> clients) {
                super.onPostExecute(clients);
                Logger.logLiveData("Set value for ViewModel");
                setValue(clients);
            }
        }.execute();
    }
}

我的ViewModel类

public class ClientViewModel extends AndroidViewModel {
    private final ClientLiveData data;

    public ClientViewModel(Application application) {
        super(application);
        data = new ClientLiveData(application);
    }

    public LiveData<List<Client>> getData(){
        return data;
    }
}

我在我的MainActivity中使用它:

    clientViewModel = ViewModelProviders.of(this).get(ClientViewModel.class);
    clientViewModel.getData().observe(this, new Observer<List<Client>>() {
        @Override
        public void onChanged(@Nullable List<Client> clients) {
            Logger.logLiveData("Notify adapter dataset changed");
            if (clientsAdapter != null) clientsAdapter.notifyDataSetChanged();
        }
    });

在我的模拟测试用例中,我首先从db中删除了所有客户端,而不是从原始json中加载一些客户端,将它们保存到db中。 我可以从AlertDialog添加新客户端,如下所示:

@OnClick (R.id.addClient_button)
public void onClick() {
    final LinearLayout container = new LinearLayout(this);
    container.setOrientation(LinearLayout.VERTICAL);
    final EditText clientNameText = new EditText(this);
    final EditText clientSpText = new EditText(this);
    container.addView(clientNameText);
    container.addView(clientSpText);
    AlertDialog.Builder builder = new AlertDialog.Builder(this)
            .setTitle("Add new client")
            .setView(container);
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String clientName = clientNameText.getText().toString();
            String clientSp = clientSpText.getText().toString();
            Client client = new Client(clientName, clientSp, "", 1, "1. Rendelő", "www.obudamaganrendelo.hu");
            client.save();
            dialog.dismiss();
            LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(new Intent(DATA_CHANGED_FILTER));
        }
    });
    builder.show();
}

正如我写的那样工作正常,在我从AlertDialog添加新客户端后,适配器更新。 但如果有人确认这种实现是使用ViewModel和LiveData的正确方法,那将是很好的。 感谢

0 个答案:

没有答案