https://kotlinlang.org logo
#compose
Title
# compose
a

althaf

10/28/2023, 4:32 AM
Hi all, I'm talking with respect to Compose + Android + ViewModel, i believe i'm taking to the right channel . I have have view model where certain flow observers are initialized, in the init { } part of the view model. Due to recomposition the init { } is getting called multiple times and events are being delivered to two different instance of viewmodel . Ideally i assume there is only one view model in action. I'm not sure if i'm doing anything wrong here.
Copy code
@Composable
fun KioskLoginScreen(
    viewModel: KioskLoginViewModel,
    navigateToKioskActivate: () -> Unit,
    navigateToKioskFailure: () -> Unit
) {  .... } 

@HiltViewModel
class KioskLoginViewModel @Inject constructor(
    context: Application,
    private val printerDevice: PrinterDevice,
) {
    init {
        Timber.i("vm $this")
        viewModelScope.launch {
            printerDevice.onDeviceStateChange.distinctUntilChanged().collectLatest {
                Timber.i("vm printer state $it")
                when (it) {
                    PrintingAllowed -> {
                        isPrintingAllowed = true
                        printerDevice.requestDeviceData(PrinterDeviceDataReq("${Date()}\n"))
                    }
                }
            }
        }
    }
I can see that Printing Allowed is getting collected twice from two different instances
🧵 1
is there any special treatment that we have to have with init { } block when using composable ?
c

cah

10/28/2023, 11:59 AM
Where are you actually creating your view model
a

althaf

10/28/2023, 2:03 PM
it is injected via hilt
Copy code
composable(kioskLoginRoute) {
    Timber.i("kioslogin route")
    KioskLoginScreen(
        hiltViewModel(),
        navigateToKioskActivate = {
            navigateToKioskActivate.invoke()
        },
        navigateToKioskFailure = {
            navigateToLoginFailure.invoke()
        }
    )
}