'Share factory view model between fragment and activity in JAVA

I have this

class ForceUpdateViewModelFactory(
    private val mApplication: Application,
    private val mForceType: ForceUpdateType
) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        require(modelClass == ForceUpdateViewModel::class.java) {
            "Unsupported model class: $modelClass"
        }
        return ForceUpdateViewModel(mApplication, mForceType) as T
    }
}

and I use it in a Fragment.

    class ForceUpdateViewModel(
    application: Application,
    forceType: ForceUpdateType
) :
    AndroidViewModel(application) {

    private val mUpdatePickataleEvent = LiveEvent<Void>()
    private val mMaybeLaterEvent = LiveEvent<Void>()

    val maybeLaterBtnVisibility: LiveData<Int> = getApplication<App>().configManager
        .effectiveConfigurationSingle
        .map { config ->
            if (forceType == ForceUpdateType.HARD) View.VISIBLE else View.GONE
        }.toObservable().asLiveData()

    fun getUpdatePickataleEvent(): LiveData<Void> = mUpdatePickataleEvent

    fun getMaybeLaterEvent(): LiveData<Void> = mMaybeLaterEvent

    fun onUpdatePickataleBtnClick() {
        mUpdatePickataleEvent.raise()
    }

    fun onMaybeLaterBtnClick() {
        mMaybeLaterEvent.raise()
    }

}

The problem is that I would like to listen for the getMaybeLaterEvent in the parent Activity, but that Activity is in Java. I have no idea how to share the view model with the Activity in this case. Normally, I THINK, I'd do it by using val sharedViewModel: MyViewModel by activityViewModels() or something of the sorts, but i have no idea how to do that in Java.



Solution 1:[1]

When you use by activityViewModels() in a Fragment, that's equivalent to using by viewModels() in an Activity. It's a ViewModel scoped to the associated Activity lifecycle either way.

Since you want a ViewModel reference in your Activity and you want to keep it Java, you can't use a property delegate. This would be the equivalent of by viewModels { ForceUpdateViewModelFactory() } in the Activity:

private ForceUpdateViewModelFactory viewModel;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //...

    viewModel = new ViewModelProvider(this, new ForceUpdateViewModelFactory())
        .get(ForceUpdateViewModel.class);

    //...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tenfour04