Skip to content

Creating first Store

Vyacheslav Vorozheykin edited this page May 31, 2020 · 4 revisions

What's a Store? Store is a middleman between your UI and business logic, between View and Model. If we look at that as on the black box, we'll probably see something like that:

User interact with View; View sends Events to Store, Store updates UI by sending updated State and new Actions.

So, let's write your first Store and bind it to our view.

Store:

import com.github.c5fr7q.jungle.Store
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

class MyStore : Store<Nothing, Nothing, Nothing>(
	foregroundScheduler = AndroidSchedulers.mainThread(),
	backgroundScheduler = Schedulers.computation()
)

View:

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.github.c5fr7q.jungle.MviView

class MyFragment : Fragment(), MviView<Nothing, Nothing> {

	lateinit var store: MyStore

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		store = MyStore()
	}

	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
		super.onViewCreated(view, savedInstanceState)
		store.attach(view = this)
	}

	override fun onDestroyView() {
		super.onDestroyView()
		store.detach()
	}
}

For that example you'll need to add RxAndroid dependency. Most probably you'll need to do it in any case.

Also, you can use custom view with custom lifecycle or Activity instead of Fragment as View.

In this example we just bind and unbind our MyStore by calling attach and detach. After binding it's ready for consuming Events, making some magic under the hood and then sending Actions and State updates to our View.

Let's look at library's Store in detail:

abstract class Store<Event, State, Action>

It has 3 generic parameters: Event, State, Action. If your View woun't use some of them, just use Nothing. Looking ahead I highly recommend you to use sealed class for Event and Action and data class for State. Your MviView's and Store's State and Action should be of the same types.

Clone this wiki locally