'Android GlobalScope.launch and viewModelScope different behaviour

I'm doing some tests and I cannot understand the different behaviour when I use the GlobalScope.launch and viewModelScope CoroutineScope

I have the following code in a viewModel:

Log.d("init")
GlobalScope.launch((Dispatchers.Main)) {
    repository
        .storedItemsListener()
        .onStart {
            Log.d("onStart")
        }
        .onEach {
            Log.d("onEach")
        }
        .onEmpty {
            Log.d("onEmpty")
        }
        .onCompletion {
            Log.d("onCompletion")
        }
        .launchIn(this)
}

Whenever the database is updated with items, storedItemsListener logs Storage Updated

At app launch, I perform a network request that updates storage with items. I then do a pull to refresh that performs a new request that also stores items on the database. With the above code, I have these logs:

// After app launch
init
onStart
Storage Updated //when the listener on the database is triggered
onEach
//After pull to refresh, although I know I store items on the database, no logs are produced. It seems that is the coroutine scope is dead and stops responding.

I then change the above code to use viewModel (.launchIn(viewModelScope)). I then obtain the logs that I expect.

// After app launch
init
onStart
Storage Updated //when the listener on the database is triggered
onEach
Storage Updated //when storage is updated with network request result
onEach
//After pull to refresh
Storage Updated //when storage is updated with network request result
onEach

My question is this. Shouldn't GlobalScope.launch be kept “alive” and notify me of all storage updates?

Please note that I want to keep this mechanism alive always and not only bound to a viewModel scope, and this is why I've chosen Global scope. The above description is a simplified version of what I need.



Sources

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

Source: Stack Overflow

Solution Source