android – Injecting viewmodels into fragment when multiple instances of fragment exist-ThrowExceptions

Exception or error:

I am using the Toothpick dependency injection framework for an Android application and I’m having problems injecting android viewmodels into fragments when multiple instances of the same fragment exists on the backstack. I would like each fragment instance to get its own viewmodel instance, but the problem is that only a single viewmodel is created and shared across all fragment instances.

I have created a sample project demonstrating the issue. A single activity contains a single fragment with an android viewmodel. Multiple instances of this activity is created and placed on the activity backstack.

This is my Activity:

class MainActivity : FragmentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.my_layout)
    }
}

it contains this layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment
        android:id="@+id/main_fragment"
        android:name="no.knowit.android.tptest.MainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

MainFragment:

class MainFragment : Fragment() {

    companion object {
        const val TAG = "MainFragment"
    }

    @Inject
    lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openScope()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val v =  inflater.inflate(R.layout.main_fragment_layout, container, false)
        v.findViewById<Button>(R.id.spawn_button).setOnClickListener {
            Log.i(TAG, "spawn")
            val i = Intent(context, MainActivity::class.java)
            startActivity(i)
        }
        return v
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.i(TAG, "fragment  " + System.identityHashCode(this))
        Log.i(TAG, "viewModel " + System.identityHashCode(viewModel))
        Log.i(TAG, "liveData  " + System.identityHashCode(viewModel.myLiveData))
    }

    protected fun openScope() {
        val scope = KTP.openScopes(ApplicationScope::class.java)
            .openSubScope(ViewModelScope::class.java)
        installViewModelBindings(scope)

        scope.closeOnViewModelCleared(this)
            .openSubScope(activity!!)
            .closeOnDestroy(activity!!)
            .openSubScope(this)
            .closeOnDestroy(this)

        scope.inject(this)
    }

    private fun installViewModelBindings(scope: Scope) {
        scope.installViewModelBinding<MainViewModel>(this)
    }
}

MainViewModel:

class MainViewModel : ViewModel() {

    @Inject
    lateinit var myLiveData: MyLiveData
}

MyLiveData:

class MyLiveData @Inject constructor(): LiveData<Int>() {
}

Output:

2020-02-18 09:12:56.325 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  45659892
2020-02-18 09:12:56.326 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:12:56.326 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:03.472 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  8599012
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:13:03.632 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:05.194 23253-23253/no.knowit.android.tptest I/MainFragment: spawn
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: fragment  130024810
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: viewModel 236316818
2020-02-18 09:13:05.289 23253-23253/no.knowit.android.tptest I/MainFragment: liveData  241221950
2020-02-18 09:13:06.436 23253-23253/no.knowit.android.tptest I/MainFragment: spawn

As you can see, new fragments are created, but share the same viewmodel and livedata.
I want to create a new viewmodel/livedata for each fragment, and these viewmodels should exist in the viewmodel scope. How can I accomplish this?

How to solve:

You could use a custom ViewModelFactory

@Singleton
class ViewModelFactory @Inject constructor() :
            ViewModelProvider.NewInstanceFactory() {

            override fun <T : ViewModel> create(modelClass: Class<T>) =
                Toothpick.openScope(ApplicationScope::class.java).getInstance(modelClass) as T
        }

and use it in your fragments/activities

@Inject
lateinit var viewModelFactory: ViewModelFactory

val mainViewModel = ViewModelProviders.of(this, viewModelFactory).get(MainViewModel::class.java)

Leave a Reply

Your email address will not be published. Required fields are marked *