Skip to content

Snappy1

  • Home
  • Android
  • What
  • How
  • Is
  • Can
  • Does
  • Do
  • Why
  • Are
  • Who
  • Toggle search form

[FIXED] android – How to work properly with coroutines in delegated class?

Posted on November 11, 2022 By

Solution 1 :

First, I’d give your worker class a CoroutineScope property in its constructor for it to use:

class MyDelegateImpl(val scope: CoroutineScope) : MyDelegate {
    override fun doWork() {
        var job = scope.async(Dispatcher.Default) {
            // .....
        }
        .....
    }
}

The next part is kind of awkward. You would usually want to use the provided viewModelScope since it’s already available and set up to cancel itself appropriately. But it’s created lazily, so it’s not available during class construction time such that you could pass it to a delegate.

I think in this case, I would shadow the viewModelScope extension property so you aren’t creating a redundant scope. You need to clean it up in onCleared().

It needs to be in the primary constructor so it can be passed to the delegate, but you want to encapsulate its creation, so I’d make the primary constructor private and create it in a public secondary constructor.

class MainViewModel private constructor(
    val viewModelScope: CoroutineScope,
    application: Application
): AndroidViewModel(application), MyDelegate by MyDelegateImpl(viewModelScope) {
    
    constructor(application: Application): this(
        CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate),
        application
    )

    override fun onCleared() {
        viewModelScope.cancel()
    }
}

Problem :

I would need advice on how to properly pass a coroutine context or scope to a deledate class. I have this base:

interface MyDelegate {
    fun doWork()
}

class MyDelegateImpl() : MyDelegate {
    override fun doWork() {
        var job = async(Dispatcher.Default) {
            // .....
        }
        .....
    }
}

class MainViewModel(application: Application): AndroidViewModel(application), CoroutineScope, MyDelegate by MyDelegateImpl() {
    .....
}

class MainActivity : AppCompatActivity() {
    .....
    private lateinit var mainViewModel: MainViewModel
    
    .....
    
    private fun initialize() {
        .....
        mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
    }
    
    fun doAction() {
        mainViewModel.doWork()
    }
}

When building, it throws an error for async in doWork():

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public fun CoroutineScope.async(context: CoroutineContext = …, start: CoroutineStart = …, block: suspend CoroutineScope.() -> TypeVariable(T)): Deferred<TypeVariable(T)> defined in kotlinx.coroutines

I tried to extend MyDelegateImpl with the CouroutineScope interface:

class MyDelegateImpl(override val coroutineContext: CoroutineContext) : MyDelegate, CoroutineScope {
    .....
}

but then I don’t know how I should pass it in MainViewModel, of course it’s not possible in the list of interfaces.

READ  [FIXED] android - Drawer Navigation menu click listener is not working How to solve this?
Powered by Inline Related Posts

Comments

Comment posted by Petr Daňa

It works, thanks a lot! Just a small correction to your code – the secondary constructor should have “this” as an ancestor, not “super”

Android Tags:android, delegates, kotlin, kotlin-coroutines

Post navigation

Previous Post: [FIXED] Unable to connect Firebase in Android Emulator for Flutter Project
Next Post: [FIXED] android – Highlight only one Card in Compose through selection

Related Posts

[FIXED] Android Facebook Key Hashes Configuration Android
[FIXED] android – How to use flutter hot reload in console? Android
[FIXED] Google signin api not working android studio using firebase Android
[FIXED] android – how to use Coroutine in kotlin to call a function every second Android
[FIXED] firebase – Android studio new update version 4.0 says Kotlin is incompatible with this new build Android
[FIXED] android – How to have border radius in flutter video player? Android

Archives

  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuándo
  • ¿Cuántas
  • ¿Cuánto
  • ¿Qué
  • Android
  • Are
  • At
  • C'est
  • Can
  • Comment
  • Did
  • Do
  • Does
  • Est-ce
  • Est-il
  • For
  • Has
  • Hat
  • How
  • In
  • Is
  • Ist
  • Kann
  • Où
  • Pourquoi
  • Quand
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welchen
  • Welcher
  • Welches
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Who's
  • Why
  • Wie
  • Will
  • Wird
  • Wo
  • Woher
  • you can create a selvedge edge: You can make the edges of garter stitch more smooth by slipping the first stitch of every row.2022-02-04
  • you really only need to know two patterns: garter stitch

Recent Posts

  • What is a good substitute for condensed milk?
  • ¿Como el cuerpo te avisa cuando te va a dar un infarto?
  • What is the luxury brand of Jaguar?
  • Who is Big poppa baseball player?
  • What material are foam runners?

Recent Comments

No comments to show.

Copyright © 2023 Snappy1.

Powered by PressBook Grid Dark theme