or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

application-setup.mdcontext-access.mddependency-injection.mdindex.mdmodule-management.mdscope-management.md

context-access.mddocs/

0

# Context Access

1

2

Functions for accessing the current Koin application instance and scope within Compose functions, providing fallback mechanisms to ensure reliable access to dependency injection context.

3

4

## Capabilities

5

6

### Get Koin Application

7

8

Retrieve the current Koin application from the composition with automatic fallback to the default platform context.

9

10

```kotlin { .api }

11

/**

12

* Retrieve the current Koin application from the composition.

13

* Falls back to default context if composition context is not available.

14

*

15

* @return Current Koin application instance

16

* @throws Exception if no Koin context is available

17

*/

18

@Composable

19

fun getKoin(): Koin

20

```

21

22

**Usage Examples:**

23

24

```kotlin

25

import org.koin.compose.getKoin

26

27

@Composable

28

fun DiagnosticsScreen() {

29

val koin = getKoin()

30

31

// Access Koin application properties

32

val logger = koin.logger

33

val scopeRegistry = koin.scopeRegistry

34

35

// Create custom scopes

36

val customScope = koin.createScope<MyScope>("custom-scope-id")

37

38

// Log current state

39

LaunchedEffect(Unit) {

40

logger.info("Current Koin instance: $koin")

41

logger.info("Active scopes: ${scopeRegistry.size}")

42

}

43

}

44

45

@Composable

46

fun ManualDependencyAccess() {

47

val koin = getKoin()

48

49

// Manually get dependencies (alternative to koinInject)

50

val userService = koin.get<UserService>()

51

val apiClient = koin.get<ApiClient>(qualifier = named("public"))

52

53

// Access with parameters

54

val sessionService = koin.get<SessionService> {

55

parametersOf("user-123")

56

}

57

}

58

```

59

60

### Get Current Scope

61

62

Retrieve the current Koin scope from the composition with automatic fallback to root scope.

63

64

```kotlin { .api }

65

/**

66

* Retrieve the current Koin scope from the composition

67

* Falls back to root scope if composition scope is not available or closed

68

*

69

* @return Current Koin scope instance

70

* @throws Exception if no Koin scope is available

71

*/

72

@Composable

73

fun currentKoinScope(): Scope

74

```

75

76

**Usage Examples:**

77

78

```kotlin

79

import org.koin.compose.currentKoinScope

80

81

@Composable

82

fun ScopeAwareComponent() {

83

val currentScope = currentKoinScope()

84

85

// Check scope properties

86

val scopeId = currentScope.id

87

val isRootScope = currentScope.isRoot

88

val isClosed = currentScope.closed

89

90

// Use scope directly for dependency resolution

91

val service = currentScope.get<MyService>()

92

93

Text("Current scope: $scopeId (root: $isRootScope)")

94

}

95

96

@Composable

97

fun ScopeInspector() {

98

val scope = currentKoinScope()

99

100

// Access scope metadata

101

LaunchedEffect(scope) {

102

scope.logger.debug("Accessing scope: ${scope.id}")

103

104

// Check if specific dependency exists in this scope

105

val hasUserService = try {

106

scope.get<UserService>()

107

true

108

} catch (e: Exception) {

109

false

110

}

111

112

scope.logger.info("UserService available in scope: $hasUserService")

113

}

114

}

115

```

116

117

## Composition Local Integration

118

119

Both functions integrate with Compose's CompositionLocal system:

120

121

### LocalKoinApplication

122

123

```kotlin { .api }

124

/**

125

* Current Koin Application context, as default with Default Koin context

126

*/

127

val LocalKoinApplication: ProvidableCompositionLocal<Koin>

128

```

129

130

### LocalKoinScope

131

132

```kotlin { .api }

133

/**

134

* Current Koin Scope, as default with Default Koin context root scope

135

*/

136

val LocalKoinScope: ProvidableCompositionLocal<Scope>

137

```

138

139

**Usage with CompositionLocalProvider:**

140

141

```kotlin

142

import androidx.compose.runtime.CompositionLocalProvider

143

import org.koin.compose.LocalKoinApplication

144

import org.koin.compose.LocalKoinScope

145

146

@Composable

147

fun CustomKoinProvider(

148

customKoin: Koin,

149

customScope: Scope,

150

content: @Composable () -> Unit

151

) {

152

CompositionLocalProvider(

153

LocalKoinApplication provides customKoin,

154

LocalKoinScope provides customScope

155

) {

156

content()

157

}

158

}

159

```

160

161

## Error Handling and Fallbacks

162

163

### getKoin() Error Handling

164

165

The function includes comprehensive error handling with fallback mechanisms:

166

167

```kotlin

168

// Internal implementation with fallback

169

@Composable

170

fun getKoin(): Koin = currentComposer.run {

171

try {

172

consume(LocalKoinApplication)

173

} catch (e: Exception) {

174

KoinPlatform.getKoinOrNull()?.let {

175

it.logger.debug("Error while accessing Koin context. Fallback on default context ...")

176

it

177

} ?: error("Can't get Koin context due to error: $e")

178

}

179

}

180

```

181

182

### currentKoinScope() Error Handling

183

184

The function handles closed scope exceptions gracefully:

185

186

```kotlin

187

// Internal implementation with fallback

188

@Composable

189

fun currentKoinScope(): Scope = currentComposer.run {

190

try {

191

consume(LocalKoinScope)

192

} catch (e: ClosedScopeException) {

193

KoinPlatform.getKoinOrNull()?.let {

194

it.logger.debug("Error while accessing Koin scope. Fallback on default root scope...")

195

it.scopeRegistry.rootScope

196

} ?: error("Can't get Koin scope due to error: $e")

197

}

198

}

199

```

200

201

## Advanced Usage Patterns

202

203

### Context Validation

204

205

```kotlin

206

@Composable

207

fun ValidatedKoinAccess() {

208

val koin = try {

209

getKoin()

210

} catch (e: Exception) {

211

null

212

}

213

214

if (koin != null) {

215

// Koin is available

216

val service = koin.get<MyService>()

217

ServiceContent(service)

218

} else {

219

// Koin not available, show error or fallback

220

Text("Dependency injection not available")

221

}

222

}

223

```

224

225

### Scope Lifecycle Monitoring

226

227

```kotlin

228

@Composable

229

fun ScopeLifecycleMonitor() {

230

val scope = currentKoinScope()

231

232

DisposableEffect(scope) {

233

scope.logger.debug("Scope ${scope.id} entered composition")

234

235

onDispose {

236

scope.logger.debug("Scope ${scope.id} left composition")

237

}

238

}

239

}

240

```

241

242

### Manual Dependency Resolution

243

244

```kotlin

245

@Composable

246

fun ManualResolution() {

247

val koin = getKoin()

248

val scope = currentKoinScope()

249

250

// Different ways to resolve dependencies

251

val service1 = koin.get<MyService>() // From Koin instance

252

val service2 = scope.get<MyService>() // From specific scope

253

val service3 = koinInject<MyService>() // Using koinInject (recommended)

254

255

// All three approaches can yield the same or different instances

256

// depending on scope configuration

257

}

258

```

259

260

## Core Types

261

262

```kotlin { .api }

263

// Core Koin interfaces

264

interface Koin {

265

val logger: Logger

266

val scopeRegistry: ScopeRegistry

267

fun <T : Any> get(clazz: KClass<T>, qualifier: Qualifier? = null): T

268

fun <T : Any> get(qualifier: Qualifier? = null, parameters: ParametersDefinition): T

269

fun createScope(scopeId: String): Scope

270

fun createScope<T>(scopeId: String): Scope

271

}

272

273

interface Scope {

274

val id: String

275

val isRoot: Boolean

276

val closed: Boolean

277

val logger: Logger

278

fun <T : Any> get(clazz: KClass<T>, qualifier: Qualifier? = null): T

279

fun <T : Any> getWithParameters(clazz: KClass<T>, qualifier: Qualifier?, parameters: ParametersHolder): T

280

fun close()

281

}

282

283

// Composition local types

284

interface ProvidableCompositionLocal<T> {

285

val defaultFactory: () -> T

286

}

287

```

288

289

## Platform Differences

290

291

The fallback mechanisms work differently across platforms:

292

293

### Android

294

Falls back to `KoinPlatform.getKoin()` which looks for Application-level Koin setup

295

296

### JVM/Desktop

297

Falls back to global Koin instance managed by `KoinPlatform`

298

299

### JavaScript/WebAssembly/Native

300

Falls back to platform-specific Koin platform implementations

301

302

## Error Types

303

304

```kotlin { .api }

305

// Common exceptions

306

class ClosedScopeException : Exception()

307

class UnknownKoinContext : Exception()

308

class NoBeanDefFoundException : Exception()

309

```

310

311

Common error scenarios:

312

- **UnknownKoinContext**: No Koin context available in composition or platform

313

- **ClosedScopeException**: Trying to access a scope that has been closed

314

- **Composition errors**: Issues with CompositionLocal access during recomposition