0

In my task I need to fetch list of bikes.

I made BikesApi and put some bikes into a list. In MovieRepository implementation I overrided function getBikes that returns now Flow<List>>.

val BikeZ : Flow<List<Bike>> = flow{
            while(true){
                val lastBikeX = bikeApi.getBikes()
                emit(lastBikeX)
                kotlinx.coroutines.delay(1000)
            }
        }
        return BikeZ

In BikeViewModel I implemented it like this, It gets MovieRepository (Koin):

public fun getPopularBikes() = flow<Bike> {
    val bikesList = repository.getPopularBikes().collect()
    return@flow bikesList
}

And when I try in Compose function this:

 val viewModel = viewModel<BikeViewModel>()

I got this error: Cannot create an instance of class BikeViewModel.

java.lang.RuntimeException: 

Cannot create an instance of class BikeViewModel

I'm using Koin. I need list of Movies to implement them into UI.

EDIT: In app module i did this:

single<BikeApi>{
BikeApiImpl()
}


 single<BikeRepository>{
        BikeRepositoryImpl(get())
    }
  viewModel { BikeViewModel(get()) }

Bike api:

class BikeApiImpl : BikeApi{
    override suspend fun getPopularBikes():  List<Bike> {
        return listOf(
            Bike(
                id = 1,
                name = "Nakamura",
                isCheckedOff = true,
                bikeType = "MTB",
                overview = "None",
                picture = R.drawable.nakamura_1,
                userScore = 72.0
        )
    

I't wont return list of Bikes.

4
  • This error has nothing to do with either the Flow or Compose. It literally means that your ViewModel class doesn't have a zero argument constructor. Commented May 16, 2022 at 18:23
  • BikeViewModel has MovieRepo in Constructor is that issue ? Commented May 16, 2022 at 18:53
  • 1
    yes, if you're using Hilt, make sure your view model has @HiltViewModel annotation, as well as @Inject annotation for your constructor. If you don't use Hilt, how do you expect your repo to be injected? Commented May 16, 2022 at 19:12
  • Via constructor initialization!! I solved it. Commented May 16, 2022 at 22:07

1 Answer 1

0

Initialize your viewModel like this if you are using Koin di:

val viewModel: BikeViewModel by viewModel()

also import

import org.koin.androidx.viewmodel.ext.android.viewModel
Sign up to request clarification or add additional context in comments.

3 Comments

Not working it says; java.lang.ClassCastException: java.lang.Object cannot be cast to androidx.lifecycle.ViewModel
@Equlo post your complete code
Posted BikeApi, currently I need to implement it without Room db.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.