Can someone explain to me the write way to write t...
# compose
v
Can someone explain to me the write way to write this function. I still really struggle with coroutines:
Copy code
fun getVehicle(vehicleId: Long): Vehicle? {
        val vehicle = viewModelScope.launch {
            repository.getVehicleById(vehicleId)
        }
        return vehicle
    }
I know this is wrong. I just can't get my head around what is right.
I guess the correct answer is to create another
mutableStateOf
value. My code is going to have a `currentVehicle`and a
selectedVehicle
and a
vehicleToDelete
and should these be the vehicle IDs (from Room database) or actual entities or a DTO? All of them could be null, so it's a sea of
vehicle?.let {...}
statements because you can't ever do a simple null check with an if statement. Very frustrating way to program if you ask me.
z
You’re overthinking it. 1) Is getVehicleById a suspending function? 2) Where are you calling your getVehicle() from?
v
I've read it. It just doesn't sink into my old brain. I think in very procedural, imperative programming ways. I've never done any reactive programming before.
z
Yeah I can tell you’re trying this from top to bottom but in the reactive world it’s a bit different Basically you should have a MutableStateFlow in your ViewModel which will have the result of your getVehicleById method. Then in your Compose code you can collect this StateFlow to receive that Vehicle
I’m on mobile so it takes a long time to write code but do look at the sample code in the link above
v
Why flow? It's a single value, only ever needed in response to a deliberatey user action.
z
You can avoid Flow entirely and instead make your ViewModel dependent on Compose by using mutableStateOf
v
In this case, it was to populate a "are you sure you want to delete this vehicle" dialog. I've got it working now but it still doesn't feel natural to me.
z
The issue with not using any “reactive state holder” such as Flow is that you can’t observe the value anymore. The thing about async programming is that values are initially empty/null and then you perform an api/database call to get the value
c
I think I would try to write your code as
Copy code
suspend fun getVehicle(vehicleId: Long): Vehicle? {
        val vehicle =            repository.getVehicleById(vehicleId)
        return vehicle
    }
but of course you will need to launch a coroutine to call that method anyway. but without other info its hard to tell what you're doing and in what layer you're trying to call this code.