All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.com.copperleaf.ballast.core.BasicViewModel.kt Maven / Gradle / Ivy

There is a newer version: 4.2.1
Show newest version
package com.copperleaf.ballast.core

import com.copperleaf.ballast.BallastViewModel
import com.copperleaf.ballast.BallastViewModelConfiguration
import com.copperleaf.ballast.EventHandler
import com.copperleaf.ballast.internal.BallastViewModelImpl
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * A generic ViewModel for Kotlin targets that don't have their own platform-specific ViewModel, or for anywhere you
 * want to manually control the lifecycle of the ViewModel. BasicViewModel's lifecycle is controlled by a coroutineScope
 * provided to it upon creation. When the scope gets cancelled, the ViewModel gets closed and can not be used again.
 */
public open class BasicViewModel private constructor(
    private val impl: BallastViewModelImpl,
    private val eventHandler: EventHandler,
    coroutineScope: CoroutineScope
) : BallastViewModel by impl {

    public constructor(
        config: BallastViewModelConfiguration,
        eventHandler: EventHandler,
        coroutineScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default),
    ) : this(
        BallastViewModelImpl("BasicViewModel", config),
        eventHandler,
        coroutineScope,
    )

    init {
        impl.start(coroutineScope)
        impl.viewModelScope.launch {
            impl.attachEventHandler(eventHandler)
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy