Why does viewModelScope.launch run on the main thread by default

ViewModelScope.launch { } runs on the main thread, but also gives you the option to run other dispatchers, so you can have UI & Background operations running synchronously. For you example: fun thisWillRunOnMainThread() { viewModelScope.launch { //below code will run on UI thread. showLoadingOnUI() //using withContext() you can run a block of code on different … Read more

What does the “yield from” syntax do in asyncio and how is it different from “await”

Short answer: yield from is an old way to wait for asyncio’s coroutine. await is a modern way to wait for asyncio’s coroutine. Detailed answer: Python has generators – special kind of functions that produces a sequence of results instead of a single value. Starting with Python 3.3 yield from expression was added. It allows … Read more

What are use cases for coroutines?

One use case is a web server that has multiple simultaneous connections, with a requirement to schedule reading and writing in parallel with all of them. This can be implemented using coroutines. Each connection is a coroutine that reads/writes some amount of data, then yields control to the scheduler. The scheduler passes to the next … Read more

Suspend function ‘callGetApi’ should be called only from a coroutine or another suspend function

Suspend function should be called only from a coroutine. That means to call a suspend function you need to use a coroutine builder, e.g. launch, async or runBlocking(recommended to use only in unit tests). For example: class Activity : AppCompatActivity(), CoroutineScope { private var job: Job = Job() override val coroutineContext: CoroutineContext get() = Dispatchers.Main … Read more

Proper type annotation of Python functions with yield

I figured out the answer on my own. I searched, but found no documentation for the 3 type parameters of Generator in the official typing documentation for Python 3.5.2 – beyond a truly cryptic mention of… class typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) Luckily, the original PEP484 (that started all this) was far more helpful: “The return … Read more