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

commonMain.com.paoapps.fifi.model.ModelImpl.kt Maven / Gradle / Ivy

Go to download

Kotlin Multiplatform Mobile framework for optimal code sharing between iOS and Android.

There is a newer version: 0.0.31
Show newest version
package com.paoapps.fifi.model

import com.paoapps.fifi.api.ApiFactory
import com.paoapps.fifi.api.ClientApi
import com.paoapps.fifi.di.API_STATE_FLOW_QUALIFIER
import com.paoapps.fifi.di.DATA_CONTAINERS_QUALIFIER
import com.paoapps.fifi.di.LAUNCH_DATA_QUALIFIER
import com.paoapps.fifi.domain.LaunchData
import com.paoapps.fifi.model.datacontainer.CDataContainer
import com.paoapps.fifi.utils.flow.FlowAdapter
import com.paoapps.fifi.utils.flow.wrap
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

abstract class ModelImpl(
    scope: CoroutineScope,
): KoinComponent, Model {

    private val environmentFactory: ModelEnvironmentFactory by inject()
    private val apiFactory: ApiFactory by inject()
    private val apiFlow: StateFlow by inject>(API_STATE_FLOW_QUALIFIER)

    private val environmentSettings: EnvironmentSettings by inject()
    protected val environmentStateFlow: MutableStateFlow by lazy { MutableStateFlow(environmentSettings.environmentName?.let {
        environmentFactory.fromName(it)
    } ?: environmentFactory.defaultEnvironment) }
    override val environmentFlow: FlowAdapter by lazy { environmentStateFlow.wrap(scope) }

    override val dataContainers: MutableMap> by inject(DATA_CONTAINERS_QUALIFIER)

    override val currentEnvironment: Environment
        get() = environmentStateFlow.value

    private val launchDataModelHelper: ModelHelper by inject(LAUNCH_DATA_QUALIFIER)
    override val launchDataFlow: Flow
        get() = launchDataModelHelper.modelDataContainer.dataFlow.filterNotNull()

    init {
        scope.launch {
            environmentFlow.map { environment ->
                apiFactory.createApi(environment)
            }.collect((apiFlow as MutableStateFlow)::emit)
        }
    }

    override fun updateEnvironment(environment: Environment) {
        environmentStateFlow.value = environment
        environmentSettings.setEnvironmentName(environment.name)
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy