Home > OS >  Starting a kotlin viewModel from java code
Starting a kotlin viewModel from java code

Time:11-04

I want to init and call a kotlin viewModel from a java class.

this is my viewModel

 @HiltViewModel
class PermProdsTestViewModel @Inject constructor(
        private val prodsUseCase: ProductUseCase
) : ViewModel() {

    private val _prods = MutableStateFlow(ProdsState())

    val prods: StateFlow<ProdsState> = _prods

    fun getPermittedProducts(serviceName: String?, productTypes: List<String>?, permission: String?, subServiceName: String?, filter: Boolean?) =
            viewModelScope.launch(Dispatchers.IO) {
                permittedProdsUseCase.invoke(serviceName, productTypes, permission, subServiceName, filter).collect() {

                    when (it) {

                        is DataResult.Success -> {
                            _prods.value = ProdsState(products = it.data)
                            Timber.d("Api request success, getting results")
                        }

                        is DataResult.Error -> {
                            ProdsState(error = it.cause.localizedMessage ?: "Unexpected Error")
                            Timber.d("Error getting permitted products")
                        }

                    }
                }
            }}

and I want to call it from a java file activity and use the method.

How can i do it?

CodePudding user response:

Did you maybe forgot to put annotation @AndroidEntryPoint above your class declaration? I tried to access to your ViewModel class from java class and it works for me.

Here is my code:

@AndroidEntryPoint
public class TestActivity extends AppCompatActivity {
private PermProdsTestViewModel vm;

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

    vm = new ViewModelProvider(this).get(PermProdsTestViewModel.class);
    vm.getPermittedProducts();
}
}
  • Related