从ViewModel触发没有数据的View操作

时间:2019-02-27 20:54:13

标签: java android mvvm

我目前正在观察ViewModel中的一些数据。数据一旦更改,我的ViewModel就会被通知并运行一些计算。在那之后,它会触发一些动作。由于松散耦合,这显然不可能直接实现。因此,我创建了一个LiveData,它在计算之后发出一个值,视图可以观察到该值以触发适当的操作(即开始一个片段)。我的问题是我需要为LiveData发出一些数据,但是我不需要任何数据即可触发该操作。

示例:

public class LandingViewModel extends ViewModel {
    private static final String TAG = "LandingViewModel";

    private final SessionKeyDao sessionKeyDao;
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private final MutableLiveData<Void> showGameFragment = new MutableLiveData<>();

    @Inject
    public LandingViewModel(final ProtocolMessageRepository protocolMessageRepository, final SessionKeyDao sessionKeyDao) {
        this.sessionKeyDao = sessionKeyDao;

        compositeDisposable.add(protocolMessageRepository.getStartGameReponse()
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io())
            .subscribe(this::OnStartGame, LandingViewModel::onError)
        );
    }

    private static void onError(final Throwable throwable) {
        Log.d(TAG, throwable.getMessage());
    }

    @Override
    protected void onCleared() {
        compositeDisposable.clear();
    }

    public LiveData<Void> getShowGameFragment() {
        return showGameFragment;
    }

    private void OnStartGame(final StartGameResponse startGameResponse) {
        sessionKeyDao.save(new SessionKey(startGameResponse.getSessionId()));
        showGameFragment.postValue(null);
    }
}

有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以通过工厂使用未决意图将未决意图用于视图模型的构造函数,然后将未决意图与调用send一起使用

class LandingViewModelFactory extends ViewModelProvider.NewInstanceFactory {

  PendingIntent pi;

   public LandingViewModelFactory(PendingIntent pi){
     super();
     this.pi = pi;
   }

   @NonNull
   @Override
   public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
      return (T) new LandingViewModel(pi);;
   }
}

PendingIntent pi = PendingIntent.getActivity(context, recCode, intent, flag);
// get pi to view model constructor through factory

viewModel = ViewModelProviders.of(this, new LandingViewModelFactory(pi)).get(LandingViewModel.class)   

//--------------------------------view model
public class LandingViewModel extends ViewModel {
    PendingIntent pi;

   public LandingViewModel(PendingIntent pi){
        this.pi = pi;
   }
   // then call send in view model when you need to start activity
   private void OnStartGame(final StartGameResponse startGameResponse) {
       sessionKeyDao.save(new SessionKey(startGameResponse.getSessionId()));
       pi.send();
   }
相关问题