Async Initialization - Xlopec/Tea-bag GitHub Wiki
Assume we can access our DB using the following DAO class:
class CounterDao {
// blocking call, returns an initial counter state
fun queryInitialCounter(): Int
}
Let's recall the initialization requirement we had previously. It states we must be able to initialize our application without blocking the UI thread.
We should turn blocking queryInitialCounter
invocation into non-blocking one. TEA-Bag has list of already implemented initializers. You can implement your custom Initializer as well, just make sure its and Initializer's signatures match.
So, our Initializer implementation that'd suit our needs might look like the following:
import io.github.xlopec.tea.core.Initializer
import kotlinx.coroutines.Dispatchers
fun AppInitializer(
dao: CounterDao
): Initializer<Int, Int> = Initializer(Dispatchers.IO) {
Initial(dao.queryInitialCounter())
}
Exceptions that might occur inside Initializer will be delivered to a Component's coroutine scope.
Here is a more sophisticated KMM sample that reads application preferences and based on this calculates initial application state
fun AppInitializer(
systemDarkModeEnabled: Boolean,
environment: Environment
): Initializer<AppState, Command> = Initializer(IO) {
// read filter from preferences
val filter = environment.findFilter(Regular)
// decide initial Feed screen state and set of commands to execute
val (screen, commands) = ArticlesInitialUpdate(NavigateToFeed.id, filter)
val settings = Settings(
syncWithSystemDarkModeEnabled = environment.isSyncWithSystemDarkModeEnabled(),
systemDarkModeEnabled = systemDarkModeEnabled,
userDarkModeEnabled = environment.isDarkModeEnabled()
)
Initial(AppState(screen, settings), commands)
}