0

I am adding a LiveData to represent a status. This is the ViewModel class:

public class MyViewModel extends AndroidViewModel {
    // Create a LiveData with a Status
    private MutableLiveData<Integer> status;

    public TsViewModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Integer> getCurrentStatus() {
        if (status == null) {
            status = new MutableLiveData<Integer>();
        }
        return status;
    }
    void setCurrentStatus(int stat) {
        status.setValue(stat);
    }
}

The current status is set in native code. I want this status to be updated in the custom application class. But it seems like I can't get a viewModel from that class:

public class MyApplication extends Application {

    public static Context context;
    public void onCreate() {
        super.onCreate();
        MyApplication .context = getApplicationContext();
        model = new ViewModelProvider(this).get(MyViewModel.class);  /* <---- this fails */
    }
}

The idea really is to set this status as early possible and that any observer would know. How can I acheive this?

Alif Hasnain
  • 1,176
  • 1
  • 11
  • 24
  • this livedata might live through the entire application instance since you are making it in application class. Are you sure you want that? – Cassius Jun 08 '20 at 20:33
  • You can override all your activities from a BaseActivity , and observe this state in BaseActivity. Launcher activity launches as soon as application class constructor, even cuncurently I think – Nabzi Jun 09 '20 at 05:29
  • @Cassius yes that is what I want. But the problem is liveData only lives within a viewModel. How do I get a viewModel instance in my Application class? – hammadahmed85 Jun 10 '20 at 11:52
  • @Golnar I am not sure I understand. Could you give an example? – hammadahmed85 Jun 10 '20 at 11:52

0 Answers0