Skip to content

ViewModel State In BaseViewModel With Generic Type Compiles As Any #15

Open
@KwabenBerko

Description

@KwabenBerko

I'm not sure if this is an issue with Kotlin/Native itself but I have a BaseViewModel with generic type T which is used to construct a stateflow:

abstract class BaseViewModel<T: Any>(initialState: T) : KMMViewModel() {
    protected val scope = viewModelScope.coroutineScope
    private val _state = MutableStateFlow(viewModelScope, initialState)
    @NativeCoroutinesState val state = _state.asStateFlow()

    protected fun setState(newState: T) {
        _state.value = newState
    }
}

All viewmodels in the project subclass this like so:

class CurrenciesViewModel(
    private val getCurrencies: GetCurrencies
) : BaseViewModel<CurrenciesViewModel.State>(State.Idle) {

    init {
        loadCurrencies()
    }

    sealed class State {
        object Idle : State()
        data class Content(
            val currencies: Map<String, List<Currency>>,
        ) : State()
    }
}

When using this in Xcode, viewModel.state in Swift has a type of Any, which means i have to cast it:

viewModel.state as! CurrenciesViewModel.State

Any idea why?
Thanks in advance

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions