package com.isidroid.core.ext

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

inline fun <reified T> ViewModel.listenArgument(savedStateHandle: SavedStateHandle, argument: String, crossinline onComplete: (T) -> Unit) {
    viewModelScope.launch {
        savedStateHandle.getStateFlow<T?>(argument, null)
            .filterNotNull()
            .onEach { onComplete(it) }
            .first()
    }
}
