'Is it possible to update Colors in jetpack from external API?

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 .



Solution 1:[1]

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,
                onError = 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhimanyu