Home > Software engineering >  Is it possible to update Colors in jetpack from external API?
Is it possible to update Colors in jetpack from external API?

Time:04-05

Is it possible to update Colors.kt in jetpack from external API while app is launching. More precisely I want to get color value of "primary","primaryVariant","secondary" from an external API on app launch time .

CodePudding user response:

It is very easy to implement a dynamic theme in Jetpack compose.

All you need is the state of colors stored in a variable and passed on to the theme.

Example code,

Activity

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            App()
        }
    }
}

@Composable
fun App(
    viewModel: MainActivityViewModel = hiltViewModel(),
) {
    val dynamicColors by viewModel.colors.collectAsState()
    StackOverflowAnswersTheme(
        dynamicColors = dynamicColors,
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
        ) {
            Button(
                onClick = {
                    viewModel.fetchColors()
                },
            ) {
                Text("Fetch Colors")
            }
            Text(
                text = "This is current Primary Color",
                color = MaterialTheme.colors.primary,
            )
            Text(
                text = "This is current Secondary Color",
                color = MaterialTheme.colors.secondary,
            )
            Button(
                onClick = {
                    viewModel.resetTheme()
                },
            ) {
                Text("Reset Theme")
            }
        }
    }
} 

ViewModel

class MainActivityViewModel : ViewModel() {
    private var _colors: MutableStateFlow<Colors?> = MutableStateFlow(
        value = null
    )
    val colors: StateFlow<Colors?> = _colors

    fun fetchColors() {
        viewModelScope.launch(Dispatchers.IO) {
            delay(1000L)
            _colors.value = Colors(
                primary = Color.Green,
                primaryVariant = Color.Black,
                secondary = Color.DarkGray,
                secondaryVariant = Color.LightGray,
                background = Color.White,
                surface = Color.White,
                error = Color.Red,
                onPrimary = Color.Blue,
                onSecondary = Color.Cyan,
                onBackground = Color.LightGray,
                onSurface = Color.White,
                one rror = Color.Red,
                isLight = true,
            )
        }
    }

    fun resetTheme() {
        _colors.value = null
    }
}

The fetchColors() method is used to mock an API call and make the actual API call there.

  • Related