Search code examples
androidkoin

SharedViewModel from koin not working with MapFragment


The sharedViewModel is not being recognized:

class MyMapFragment: MapFragment(), OnMapReadyCallback, GoogleMap.OnMapLoadedCallback {

    private val viewModel: MyViewModel by sharedViewModel()

    private var map: GoogleMap? = null

    override fun onMapReady(googleMap: GoogleMap?) {
        map = googleMap
        map?.setOnMapLoadedCallback(this)
    }

    override fun onMapLoaded() {
    }
}

Is this a known issue? I couldn't find anything. By the way, it works with a "regular" fragment.


Solution

  • In koin there are 2 extension files FragmentExt for androidx.fragment.app.Fragment and android.support.v4.app.Fragment wich offer the extension function sharedViewModel(). MapFragment extends android.app.Fragment and therefore the extension function is not available there.

    You can use SupportMapFragment which extends android.support.v4.app.Fragment and includes your desired extension function instead of MapFragment