0

I need to make callbacks from Service to catch them in my ViewModel, operate on data and convert to LiveData. I'm trying to make callbacks like this:

class MyService : Service() {

    interface Callbacks {
        fun onForegroundStatusChanged(isForeground: Boolean)
        fun onLocationChanged(location: Location)
    }

    private var callbacks: Callbacks? = null

    override fun onCreate() {
        super.onCreate()
        callbacks = this@LocationService as Callbacks?
    }

But IDE telling me that this as cast will never succeed. Can you help me with this callbacks?

SoulReaver313
  • 365
  • 1
  • 11
  • Does this answer your question? [Service callback to Activity in Android](https://stackoverflow.com/questions/23771581/service-callback-to-activity-in-android) – Hayk Mkrtchyan Jun 01 '22 at 07:24
  • @HaykMkrtchyan unfortunately not. I'm trying to create callback straight to VM avoiding Activity – SoulReaver313 Jun 01 '22 at 07:25
  • If you have already declared `var callbacks: Callbacks?`, assuming LocationService adheres to the interface, I don't see why an explicit cast is needed. The IDE simply maybe complaining that `as` is unnecessary. – Mohammed Aquib Azad Jun 01 '22 at 07:40
  • @MohammedAquibAzad if i will just delete this cast i'm getting: `Type mismatch. Required: MyService.Callbacks? Found: MyService` – SoulReaver313 Jun 01 '22 at 08:19

0 Answers0