Skip to content

Instantly share code, notes, and snippets.

View JoseAlcerreca's full-sized avatar

Jose Alcérreca JoseAlcerreca

View GitHub Profile
class MyViewModel(authManager..., repository...) : ViewModel() {
private val userId: LiveData<String?> =
authManager.observeUser().map { user -> user.id }.asLiveData()
val result: LiveData<Result<Item>> = userId.switchMap { newUserId ->
liveData { emit(repository.fetchItem(newUserId)) }
}
}
class MyViewModel(...) : ViewModel() {
val result: StateFlow<Result<UiState>> = flow {
emit(repository.fetchItem())
}.stateIn(
scope = viewModelScope,
started = WhileSubscribed(5000), // Or Lazily because it's a one-shot
initialValue = Result.Loading
)
}
class MyViewModel(...) : ViewModel() {
val result: LiveData<Result<UiState>> = liveData {
emit(Result.Loading)
emit(repository.fetchItem())
}
}
class MyViewModel {
private val _myUiState = MutableStateFlow<Result<UiState>>(Result.Loading)
val myUiState: StateFlow<Result<UiState>> = _myUiState
// Load data from a suspend fun and mutate state
init {
viewModelScope.launch {
val result = ...
_myUiState.value = result
}
@JoseAlcerreca
JoseAlcerreca / MyViewModel.kt
Created May 11, 2021 11:15
Migrating from LiveData to Kotlin's Flow
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class MyViewModel {
private val _myUiState = MutableLiveData<Result<UiState>>(Result.Loading)
val myUiState: LiveData<Result<UiState>> = _myUiState
// Load data from a suspend fun and mutate state
init {
viewModelScope.launch {
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
@HiltAndroidTest
@UninstallModules(CoroutinesModule::class)
@RunWith(AndroidJUnit4::class)
class AgendaTest {
@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
@InstallIn(ApplicationComponent::class)
@Module
object TestCoroutinesModule {
@DefaultDispatcher
@Provides
fun providesDefaultDispatcher(): CoroutineDispatcher =
AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
open class MainTestApplication : Application() {
override fun onCreate() {
// ThreeTenBP for times and dates, called before super to be available for objects
AndroidThreeTen.init(this)
Timber.plant(Timber.DebugTree())
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
// With Dagger2 or dagger.android
class MainTestApplication : MainApplication() {
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerTestAppComponent.builder().create(this)
}
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
@CustomTestApplication(MainTestApplication::class)
class CustomTestRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, name: String?, context: Context?): Application {
return super.newApplication(cl, CustomTestRunner_Application::class.java.name, context)
}
}