Skip to content

Instantly share code, notes, and snippets.

View JoseAlcerreca's full-sized avatar

Jose Alcérreca JoseAlcerreca

View GitHub Profile
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
suspend fun printPrimes() {
while(true) { // Ok-ish because we call delay inside
// Compute
delay(1000)
}
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
suspend fun printPrimes() {
while(isActive) {
// Compute
}
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
liveData(Dispatchers.IO) {
emit(LOADING_STRING)
emitSource(dataSource.fetchWeather())
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
private val itemId = MutableLiveData<String>()
val result = itemId.switchMap {
liveData { emit(fetchItem(it)) }
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class MyViewModel : ViewModel() {
val result = liveData {
emit(doComputation())
}
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
// Don't do this. Use liveData instead.
class MyViewModel : ViewModel() {
private val _result = MutableLiveData<String>()
val result: LiveData<String> = _result
init {
viewModelScope.launch {
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class MyActivity : Activity {
override fun onCreate(state: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
// Run
}
<!-- Copyright 2020 Google LLC.
SPDX-License-Identifier: Apache-2.0 -->
class MainActivityViewModel : ViewModel {
init {
viewModelScope.launch {
// Do things!
}
/* Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
@Test
fun isLiveDataEmitting_getOrAwaitValue() {
viewModel.setNewValue("foo")
// Pass:
assertEquals(viewModel.liveData1.getOrAwaitValue(), "foo")
assertEquals(viewModel.liveData2.getOrAwaitValue(), "FOO")
}
/* Copyright 2019 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
@Test
fun isLiveDataEmitting_getOrAwaitValue() {
viewModel.setNewValue("foo")
// Pass:
assertEquals(viewModel.liveData1.getOrAwaitValue(), "foo")
assertEquals(viewModel.liveData2.getOrAwaitValue(), "FOO")
}