Skip to content

Instantly share code, notes, and snippets.

class MyViewModel : ViewModel() {
/**
* This is the job for all coroutines started by this ViewModel.
* Cancelling this job will cancel all coroutines started by this ViewModel.
*/
private val viewModelJob = SupervisorJob()
/**
* This is the main scope for all coroutines launched by MainViewModel.
class MyViewModel : ViewModel() {
/**
* Heavy operation that cannot be done in the Main Thread
*/
fun launchDataLoad() {
viewModelScope.launch {
sortList()
// Modify UI
}
private const val JOB_KEY = "androidx.lifecycle.ViewModelCoroutineScope.JOB_KEY"
val ViewModel.viewModelScope: CoroutineScope
get() {
val scope: CoroutineScope? = this.getTag(JOB_KEY)
if (scope != null) {
return scope
}
return setTagIfAbsent(JOB_KEY,
CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate))
@MainThread
final void clear() {
mCleared = true;
// Since clear() is final, this method is still called on mock
// objects and in those cases, mBagOfTags is null. It'll always
// be empty though because setTagIfAbsent and getTag are not
// final so we can skip clearing it
if (mBagOfTags != null) {
for (Object value : mBagOfTags.values()) {
// see comment for the similar call in setTagIfAbsent
internal class CloseableCoroutineScope(
context: CoroutineContext
) : Closeable, CoroutineScope {
override val coroutineContext: CoroutineContext = context
override fun close() {
coroutineContext.cancel()
}
}
@ExperimentalCoroutinesApi
class CoroutinesTestRule(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.setMain(testDispatcher)
}
class MainViewModelUnitTest {
@get:Rule
var coroutinesTestRule = CoroutinesTestRule()
@Test
fun test() {
...
}
}
@manuelvicnt
manuelvicnt / MyViewModel.kt
Created March 21, 2019 08:11
Testing viewModelScope
class MyViewModel(dependency: ExternalDependency) : ViewModel() {
fun run() {
viewModelScope.launch {
dependency.doStuff()
}
}
}
class MyViewModelTest {
@manuelvicnt
manuelvicnt / kotlinx-html-jvm-0.6.8-diff.txt
Created April 23, 2019 14:28
Adds devsite-heading to kotlinx-html-jvm-0.6.8 library
diff --git a/generate/src/main/resources/i18Languages.xsd b/generate/src/main/resources/i18Languages.xsd
index 4e3fc1b..6825a20 100644
--- a/generate/src/main/resources/i18Languages.xsd
+++ b/generate/src/main/resources/i18Languages.xsd
@@ -134,6 +134,7 @@
<xsd:enumeration value="de-lu"/>
<xsd:enumeration value="del"/>
+ <xsd:enumeration value="dheading"/>
<xsd:enumeration value="den"/>
class MainViewModel(private val dependency: Any): ViewModel {
fun sampleMethod() {
viewModelScope.launch {
val hashCode = dependency.hashCode()
// TODO: do something with hashCode
}
}
class MainViewModelUnitTest {