在Koin MVP中提供活动

时间:2019-04-20 11:26:39

标签: android koin

我是Koin的新手(通常我使用的是Dagger),现在我无法使用MVP将View实例传递给Presenter。我去了NullPointer异常。如何将视图实例传递给我的演示者?就像Koin在View上传递null一样(在Dagger中,我将使用contributionActivityInjection

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
        at com.strangelove.dtfu.MainActivity._$_findCachedViewById(Unknown Source:25)
        at com.strangelove.dtfu.MainActivity.showText(MainActivity.kt:10)
        at com.strangelove.dtfu.MySimplePresenter.sayHelloFromActivity(MySimplePresenter.kt:7)
        at com.strangelove.dtfu.MainActivity.onCreate(MainActivity.kt:19)

演示者

class MySimplePresenter(private val repo: HelloRepository, private val mainActivityView: MainActivityView) {
    fun sayHello() = "${repo.giveHello()} from $this"

    fun sayHelloFromActivity() {
        mainActivityView.showText(sayHello())
    }
}

活动

class MainActivity : AppCompatActivity(), MainActivityView {
    override fun showText(text: String) {
        first_textView.text = firstPresenter.sayHello()
    }

    private val firstPresenter: MySimplePresenter by inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onStart() {
        super.onStart()
        firstPresenter.sayHelloFromActivity()
    }
}

查看

interface MainActivityView {
    fun showText(text: String)
}

模块

val appModule = module {
    single<HelloRepository> {
        HelloRepositoryImpl()
    }

    factory {
        MySimplePresenter(get(), get())
    }
}

val activityModule = module {
    single<MainActivityView> {
        MainActivity()
    }
}

应用程序:

class MyApplication: Application() {
    override fun onCreate() {
        super.onCreate()
        startKoin {
            androidLogger()
            androidContext(this@MyApplication)
            modules(appModule, activityModule)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试更改

factory {
    MySimplePresenter(get(), get())
}

factory { (view: MainActivityView) ->
    MySimplePresenter(get(), view)
}

在活动中:

private val firstPresenter: MySimplePresenter by inject { parametersOf(this@MainActivity) }

通过这种方式,您提供一种观点作为论据,我认为在这种情况下是理想的。